JS method to find the substring specified in the string: 1. Search by using the search method in the JavaScript String object; 2. Search for the substring specified in the string by using the match method.
The operating environment of this article: Windows 7 system, javascript version 1.8.5, Dell G3 computer.
In js, search (find) the specified substring in the string by using the search() method and match() method in the JavaScript String object.
Using the search() method
The search() method of string is used to find the specified substring in the specified string , or a substring matching a regular expression. If there is a matching substring, the starting position of the matching substring is returned; if there is no matching substring, -1 is returned.
Syntax:
string.search(regexp)
Parameter regexp: Indicates the specified substring that needs to be found, or the regular expression that needs to be matched.
Note: The search() method is case-sensitive. If you want to ignore case search, you need to append the flag i.
Example:
<div class="demo"> <p> <span id="str1"></span><br /> <span>查找:脚本语言</span><br /> <span id="str2"></span> </p> <p> <span id="str3"></span><br /> <span>查找:php</span><br /> <span id="str4"></span><br /> <span>查找:脚本语言</span><br /> <span id="str5"></span> </p> </div> <script> var str1="JavaScript是一种脚本语言, 脚本语言经常被解析"; var str2=str1.search("脚本语言"); var str3="php中文网的网址为:www.php.cn!"; var str4=str3.search("php"); var str5=str3.search("脚本语言"); document.getElementById("str1").innerHTML =str1; document.getElementById("str2").innerHTML ="返回:"+str2; document.getElementById("str3").innerHTML =str3; document.getElementById("str4").innerHTML ="返回:"+str4; document.getElementById("str5").innerHTML ="返回:"+str5; </script>
Rendering:
##Use match() method
The match() method is used to retrieve a specified value within a string, or to find a matching substring of one or more regular expressions. Syntax:string.match(searchvalue) string.match(regexp)
<div class="demo"> <p> <span id="str1"></span><br /> <span>查找:php</span><br /> <span id="str2"></span><br /> <span>查找:php(添加g)</span><br /> <span id="str3"></span><br /> <span>查找:PHP(区分大小写)</span><br /> <span id="str4"></span><br /> </p> </div> <script> var str1="php中文网的网址为:www.php.cn!"; var str2=str1.match("php"); var str3=str1.search(/php/g); var str4=str1.search("PHP"); document.getElementById("str1").innerHTML =str1; document.getElementById("str2").innerHTML ="返回:"+str2; document.getElementById("str3").innerHTML ="返回:"+str3; document.getElementById("str4").innerHTML ="返回:"+str4; </script>
##Summary: The above is the entire article Content, I hope it will be helpful to everyone’s study.
The above is the detailed content of How to find a specified substring in a string in js. For more information, please follow other related articles on the PHP Chinese website!