JS Gets the position in a string where the specified string occurs n times
- 2021-10-27 06:20:19
- OfStack
Learn about similar ways to get character positions:
charAt () Gets the character at the specified position of the string
Usage: strObj is the string object, index is the specified position, (the position starts from 0)
strObj.charAt(index)
The indexOf () method returns the first occurrence of a specified string value in a string
Usage: stringObject is a string object, searchvalue is a specified string value, and fromindex (optional) specifies the position where the string value begins to match. If none, it means starting from the position 0.
stringObject.indexOf(searchvalue,fromindex)
For example:
var str='helloworld';
var num=str.indexOf('o');// Return 4
Get down to business
Gets the position of a string value at the n occurrence of the specified string
Just like the example above, helloword, I want to get the location where the second o appears
js code: Parameters (string, string value to find, which string value to find
function find(str,cha,num){
var x=str.indexOf(cha);
for(var i=0;i<num;i++){
x=str.indexOf(cha,x+1);
}
return x;
}
Refer to this method:
ar str="Hello World!"
document.write(find(str,'o',1));// Return 7
The basic usage is like this. For a string with more than one character in the same string, just replace the corresponding 2 with the n value you want to find.
For example: Get the position where the n '/' appears in the current page url
Call the above method directly
ar str=document.URL;// Get the full path information of the current page
document.write(find(str,'/',n));