Learn about similar methods for getting character positions: charAt() Gets the character at the specified position in the stringUsage: strObj is a string object, index is the specified position (the position starts at 0) strObj.charAt(index) The indexOf() method returns the index of the first occurrence of a specified string value in a string.Usage: stringObject is a string object, searchvalue is the specified string value, fromindex (optional) specifies the position to start matching the string value. If not, it means starting from position 0. stringObject.indexOf(searchvalue,fromindex) For example: var str = 'helloworld'; var num = str.indexOf('o'); // returns 4 Main topicGet the position of the nth occurrence of a string value in the specified string Like the example above, helloword, I want to get the position where the second o appears js code: parameter (string, string value to be searched, the string value to be searched 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; } Quote the method: ar str="Hello World!" document.write(find(str,'o',1));//Return 7 The basic usage is like this. For a string with many identical characters, just replace the corresponding 2 with the n value you want to find. For example: Get the position of the nth '/' in the current page URL Call the above method directly ar str=document.URL; //Get the complete path information of the current page document.write(find(str,'/',n)); This is the end of this article about how to get the nth occurrence of a specified string in a string with JS. For more information about how to get the nth occurrence of a specified string in a string with JS, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Ubuntu terminal multi-window split screen Terminator
>>: Summary of online MYSQL synchronization error troubleshooting methods (must read)
Preface 1. Benchmarking is a type of performance ...
I upgraded my Raspberry Pi server to Ubuntu 20 tw...
Basics The matching order of location is "ma...
Table of contents Optimizing sorting queries Avoi...
Firefox, Opera and other browsers do not support W...
Table of contents 1. Array deduplication 2. Dedup...
Responsive design is to perform corresponding ope...
CSS 3 animation example - dynamic effect of Tab b...
Overview What is harbor? The English word means: ...
Build the image There are two main ways to build ...
Table of contents 01 JavaScript (abbreviated as: ...
1. display:box; Setting this property on an eleme...
Table of contents Preface 1. What variables are p...
Before talking about OO, design patterns, and the ...
1. Cancel the blue color of the a tag when it is ...