In this article, we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript.
We can use the JavaScript string.search() method to search for a match between a regular expression in a given string.
Syntax:
let index = string.search( expression )
Parameters: This method accepts two parameters that are given below:
- String name: The string name in which we want to search for a regular expression.
- Expression: It is the pattern/substring which we want to check if it is present in the above string.
Return value: It returns the value of the index of the first matching regular expression in the given string else it returns -1. It starts from index 0, and if any alphabet is matched, it returns its corresponding index and does not check further. It returns the index of the first alphabet if any regular expression matches the corresponding string.
Example 1: We can observe that the expression ‘cie’ is present at the 31st index of the given string. More precisely, it returns the index of the first alphabet of the first match regular expression, which in this case is ‘c’ in ‘cie’. In the second case, it returns the index of the first ‘c’ alphabet whereas in the third case, it returns -1 since there is no expression ‘z’ in the given string.
JavaScript
// Taking input a string const str = "neveropen is for computer science neveropen" ; // Taking a regular expression const regexp1 = /cie/; const regexp2 = /c/; const regexp3 = /z/; // Expected Output: 31 console.log(str.search(regexp1)); // Expected Output: 21 console.log(str.search(regexp2)); // Expected Output: -1 console.log(str.search(regexp3)); |
31 21 -1
We can implement this method in an array of strings to selectively find all the matching strings against a regular expression. For this, we need to iterate all the given strings in the array and search for the regular expression in the string elements.
Example 2: For implementing this, we will use the array push() method in JavaScript that adds an element in an array from the back.
Syntax:
array.push( element1, element2, element3, ... elementN )
Example:
JavaScript
// Taking an array of str const str = [ "neveropen is computer science portal" , "I am a Geek" , "I am coder" , "I am a student" , "I am a computer science Geek" ]; // Taking a regular expression const regexp = /Gee/; let arr = []; for (let i = 0; i < str.length; i++) { if (str[i].search(regexp) != -1) { arr.push(str[i]) } } console.log(arr) |
[ 'neveropen is computer science portal', 'I am a Geek', 'I am a computer science Geek' ]
We successfully return an array of all the strings that match with a given regular expression.