JS gets the position of the nth occurrence of the specified string in a string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.