JavaScript indexOf() - how to get specific index

前端 未结 8 580
野趣味
野趣味 2021-01-18 02:02

Let\'s say I have a URL:

http://something.com/somethingheretoo

and I want to get what\'s after the 3rd instance of /?

8条回答
  •  别那么骄傲
    2021-01-18 02:23

    Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches.

    String.prototype.nthIndexOf = function(s, n) {
      var i = -1;
      while(n-- > 0 && -1 != (i = this.indexOf(s, i+1)));
      return i;
    }
    
    var str = "some string to test";
    
    alert(str.nthIndexOf("t", 3)); // 15
    alert(str.nthIndexOf("t", 7)); // -1
    alert(str.nthIndexOf("z", 4)); // -1
    
    var sub = str.substr(str.nthIndexOf("t",3)); // "test"
    

    Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in.

提交回复
热议问题