How to find if an array contains a specific string in JavaScript/jQuery ?
Last Updated :
31 Jul, 2024
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.
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=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</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:
Similar Reads
How to check if a String contains a Specific Character in PHP ?
In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
2 min read
Check If An Array of Strings Contains a Substring in JavaScript
Here are the different ways to check if an array of strings contains a substring in JavaScript 1. Using includes() and filter() methodWe will create an array of strings, then use includes() and filter() methods to check whether the array elements contain a sub-string. [GFGTABS] JavaScript const a =
4 min read
How to check if string contains only digits in JavaScript ?
A string with only digits means it consists solely of numeric characters (0-9) and contains no other characters or symbols. Here are the different methods to check if the string contains only digits. 1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string c
3 min read
How to Check if an Object has a Specific Property in JavaScript ?
In JavaScript, objects can have properties that store data or functions. Sometimes it is necessary to check whether an object has a specific property. This can be useful, for example, when you want to avoid calling a function on an object that doesn't have that function defined as a property. In thi
3 min read
How to search a string for a pattern in JavaScript ?
Here are two ways to search a string for a pattern in JavaScript. 1. Using string search() MethodThe JavaScript string search() method is used to serch a specified substing from the given string and regular expression. It returns the index of the first occurrence of the pattern or -1 if the pattern
2 min read
How to get Values from Specific Objects an Array in JavaScript ?
In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects. Table of Content Using the forEach() methodUsing the map() methodUsing the filte
2 min read
How to Check Whether a String Contains a Substring in JavaScript?
Given two strings, check if one string is substring of another. "bce" is substring of "abcde""ae" is not substring of "abcde"Empty String is a substring of all stringsUsing includes() - Most used and Simplest MethodThe includes() method checks whether a string contains a substring. [GFGTABS] JavaScr
2 min read
How to Check if a Specific Element Exists in a Set in JavaScript ?
To check if a specific element exists in a Set in JavaScript, you can use the has method. The has method returns a boolean indicating whether an element with the specified value exists in the Set Syntax:myset.has(value);Parameters:value: It is the value of the element that has to be checked if it ex
1 min read
How to check a given string is an anagram of another string in JavaScript ?
In this article, we will learn how to check a given string is an anagram of another string in JavaScript. Before that, we should learn what is an anagram. An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different te
3 min read
How to test a string as a literal and as an object in JavaScript ?
In this article, we learn how to test a string as a literal and as an object using JavaScript. What is JavaScript Literal?Literals are ways of representing fixed values in source code. In most programming languages, values are notated by integers, floating-point numbers, strings, and usually by bool
3 min read