Open In App

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

Last Updated : 07 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In order to Check if an array contains a specific string be done in many ways in Javascript. One of the most common methods to do this is by using the traditional for loop. In Javascript, we have several other modern approaches which help in finding a specific string in an array to iterate the array some more methods include using the indexOf()  method and includes()method and with the help of jQuery we have grep() method. In this article, we will explore these approaches with their example.

Approaches:

Approach 1: Using the indexOf() method

It is an inbuilt javascript method that returns the index of the first occurrence of the string to be searched which returns 1 if found and -1 if not found

Syntax:

array.indexOf(searchValue , index)
  • searchValue: It is the value that we need to search in the array.
  • Index: It is the index position to start searching in the array. If not specified, the search will start from index 0.

Example: In this example, we create an array of strings and a variable to store the search string and then we use the index of the method to look for the specific string in the array if the string is present in the array it returns 1, and if it is not present it return -1.

Javascript




const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Geeks';
  
if (array.indexOf(String) !== -1) {
    console.log(`${String} is present in the array`);
} else {
    console.log(`${String} is not present the array`);
};


Output:

Geeks is present in the array

Approach 2: Using the includes() method

It is a built-in method that returns a boolean value that indicates whether the string is present in the array or not. Here we will use it to check if a string is present in the array.

Syntax:

array.includes(searchValue, index);

Parameters:

  • searchValue: It is the value that we need to search in the array.
  • Index: It is the index position to start searching in the array. If not specified, the search will start from index 0.

Example: In this example, we will use the array includes() method to check whether the string is present in the array if the string is present in the array it returns 1, and if it is not present it returns -1 and prints the required output in the console.

Javascript




const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Computer science';
  
if (array.includes(String) !== -1) {
    console.log(`${String} is present in the array`);
} else {
    console.log(`${String} is not present the array`);
};


Output:

Computer science is present in the array

Approach 3: Using a for loop

We can iterate through the array using a for loop and check each element to see if it matches the search string and when it matches the string we break the loop and print the answer in the console.

Syntax:

for ( variable of iterableObjectName) {
    ...
}

Example: In this example, we will iterate over the elements of an array using the for loop and will search for the required string in the array when the string is found the loop will break and we will print the output in the console.

Javascript




const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Geeksforgeeks';
let found = false;
  
for (let i = 0; i < array.length; i++) {
    if (array[i] === String) {
        found = true;
        break;
    }
}
  
if (found) {
    console.log(`${String} is present in the array`);
} else {
    console.log(`${String} is not present the array`);
};


Output:

Geeksforgeeks is present in the array

Approach 4: Using grep() Method

This is a built-in function that filters out the array based on the condition it uses the filter function to filter out the specific condition and it does not affect the original array.

Syntax:

grep( array, function [, invert ] );

Parameters:

  • array: The array in which the search will be performed.
  • function: The function used to test each element of the array
  • invert: this method if true returns the elements of the array that do not satisfy the condition of the test.

Example: In this example, we will be creating an array with values in it and a value to be searched and we will use the grep() method to search for specific strings in the array by applying a condition that will return the first matched string.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        JQuery | inArray() and grep() Method
    </title>
    <script src=
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GFG Website
    </h1>
    <p id="up"></p>
    <button onclick="runGrep()">
        Search value
    </button>
    <p id="down" 
       style="color:green;"></p>
  
    <script>
      
        // Define variables
        var elUp = document.getElementById("up");
        var elDown = document.getElementById("down");
        var arr = ["GFG", "GeeksForGeeks", "Geeks", "Geek"];
        var value = "GeeksForGeeks";
          
        // Update HTML content
        elUp.innerHTML = "Click the button to search the array.<br>"
            + "Array: [" + arr + "]<br>"
            + "Search value: '" + value + "'";
          
        // Define grep() search function
        function runGrep() {
            var result = $.grep(arr, function (element) {
                return element === value;
            });
          
            if (result.length > 0) {
                elDown.innerHTML = "Found: " + result[0];
            } else {
                elDown.innerHTML = "Not found";
            }
        }
    </script>
</body>
  
</html>


Output:

Example using grep() method



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads