1.JS gets the position of the nth occurrence of the specified string in a string
Learn similar ways to get character positions:
1.1 charAt () Gets the character of the string at the specified position
Usage: Strobj is a String object, index is the specified position, (position starting from 0)
Strobj.charat (Index)
The 1.2 indexOf () method returns the position of the first occurrence of a specified string value in a string
Usage: Stringobject is a string object, Searchvalue is the specified string value, and Fromindex (optional) specifies the position at which to start matching the string value, if none, that is, starting at the 0 position.
Stringobject.indexof (Searchvalue,fromindex)
Cases:
var str= ' HelloWorld '; var num=str.indexof (' O '); // returns 4
2. The subject
Gets a string value where the nth occurrence of the specified string
Just like the example above, Helloword, I want to get the second o where it appears
JS Code: Parameter (string, to find the string value, to find the number of the string value
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; }
To refer to this method:
Ar str= "Hello world!" document.write (Find (str,' O ', 2)); // returns 7
The basic usage is this, for a string of the same character than characters string, only need to change the corresponding 2 for the n value you want to find it.
For example, get the location where nth '/' appears in the URL of the current page
Call the above method directly
AR str=document. url;//Gets the full path information of the current page document.write (Find (str,'/', n));
Get the page path method, refer to my next article:
JS gets the position of the nth occurrence of the specified string in a string