let index = string.search( expression )
Parameters: The string.search() method accepts two parameters.
- 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.
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.
array.push( element1, element2, element3, ... elementN )
['GeeksforGeeks is computer science portal', 'I am a Geek', 'I am computer science Geek'] 0: "GeeksforGeeks is computer science portal" 1: "I am a Geek" 2: "I am a computer science Geek" length: 3 [[Prototype]]: Array(0)
We successfully return an array of all the strings that match with a given regular expression.