search() is a built-in function in How to use search method, which can be used to search for matching objects between regular expressions and given string objects. In this article, we will take a closer look at the search method. Basic usage.
First let’s take a look at the basic syntax of the search method
string.search(regexp);
regexp represents a regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp using new RegExp(obj).
search() returns the index of the first match between the regular expression and the given string object, or -1 if no match is found.
Let’s look at a specific example
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> // 输入一个字符串 var string = "GeeksforGeeks"; // 获取正则表达式 var re1 = /G/; var re2 = /e/; var re3 = /s/; var re4 = /, /; // 输出匹配字母的索引 document.write(string.search(re1) + "<br>"); document.write(string.search(re2) + "<br>"); document.write(string.search(re3)+"<br>"); document.write(string.search(re4)); </script> </body> </html>
The results displayed on the browser are as follows: re4 does not find a match, so -1 is returned.
This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to use search method. For more information, please follow other related articles on the PHP Chinese website!