In the previous article "How to calculate the position of an element using js", we introduced the method of obtaining the absolute position relative to the browser window and the offset position relative to the parent node or body element. method. This time we continue to learn javascript and introduce the method of determining whether a specified substring exists in a string.
There are many methods in JavaScript to determine whether a specified substring exists, for example, by obtaining the first or last occurrence position of the substring in the string, and then determining whether the occurrence position really exists, that is, whether Has a positive integer value; if so, the specified substring exists.
How to get the first or last occurrence position of a substring in a string? Let’s look at the following example:
var str = "How do you do!"; //获取子串“do”在str字符串中第一次出现的位置 var index=str.indexOf("do"); console.log("'do'在str字符串中第一次出现的位置是:"+index);
Output result:
Because the string position starts at 0, not 1; so we The first occurrence position obtained by using str.indexOf("do")
is 4.
Look at the following example:
var str = "How do you do!"; //获取子串“do”在str字符串中最后一次出现的位置 var lastindex=str.lastIndexOf("do"); console.log("'do'在str字符串中最后一次出现的位置是:"+lastindex);
Output result:
##It can be seen that usingstr.lastIndexOf( "do")The last occurrence position obtained is 11.
var str = "How do you do!"; //获取子串“do”在str字符串中最后一次出现的位置 var index=str.indexOf("de"); var lastindex=str.lastIndexOf("de"); console.log("'de'在str字符串中第一次出现的位置是:"+index); console.log("'de'在str字符串中最后一次出现的位置是:"+lastindex);
-1 is returned.
function a(str1,str2){ var index=str1.indexOf(str2); var lastindex=str1.lastIndexOf(str2); if(index!=-1){ console.log("第一次出现的位置是:"+index+" ,因此 子串 “"+str2+"” 是存在的"); }else{ console.log("第一次出现的位置是:"+index+" ,因此 子串 “"+str2+"” 是不存在的"); } if(lastindex!=-1){ console.log("最后一次出现的位置是:"+lastindex+" ,因此 子串 “"+str2+"” 是存在的"); }else{ console.log("最后一次出现的位置是:"+lastindex+" ,因此 子串 “"+str2+"” 是不存在的"); } }
var str = "How do you do!"; a(str,"do"); a(str,"de");
The above is the detailed content of How does js know whether a given substring exists?. For more information, please follow other related articles on the PHP Chinese website!