How to find if an array contains a specific string in jQuery?

Given an array of strings, we need to find out whether it contains a specific string or not using jQuery.
Submitted by Pratishtha Saxena, on September 07, 2022

Prerequisite: Adding jQuery to Your Web Pages

An array can be a collection of strings, numbers, or both. To check whether the specified string or value is present in the array or not, we need to traverse each element at least once. If the element visited gets matched, then that value or index can be returned accordingly.

jQuery contains a method for this kind of task - jQuery.inArray() method. This method returns the index of the value that has been matched. If not, then it returns -1.

Syntax:

jQuery.inArray(value, array[]);

It takes in two parameters, namely: value and array. The value here is the string or character that we need to return the index of. Whereas the array is the array in which we need to find and check the value. This array can be predefined or it can also be defined over here. Both ways can be used.

Hence, to check whether the array contains the specific string, we'll use jQuery.inArray() method and if this returns -1 then the array does not contain the string, otherwise, it contains the target string.

Let's see the below given example.

jQuery example to find if an array contains a specific string

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Find Whether an Array Contains a Specific String Using jQuery</h2>
    <p>Write some input below and check whether it is present if the given array.</p>
    <br>
    <label>Months: </label><b><span>Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec</span></b>
    <br><br>
    <label>Enter Text: </label><input><button>Check</button><br><br>
    <h3 id="myH"></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        var arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

        $("button").click(function(){
            var name = $('input').val();
            if (jQuery.inArray(name, arr) == -1 ){
                $('#myH').html('String is NOT Present in the Array.');
            }
            else{
                $('#myH').html('String is Present in the Array.');
            }
        });
    });
  </script>
</html>

Output:

Example: Find if an array contains a specific string





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.