JavaScript indexOf() - how to get specific index

前端 未结 8 587
野趣味
野趣味 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:28

    If you want to stick to indexOf:

    var string = "http://something/sth1/sth2/sth3/"
    var lastIndex = string.indexOf("/", lastIndex);
    lastIndex = string.indexOf("/", lastIndex);
    lastIndex = string.indexOf("/", lastIndex);
    string = string.substr(lastIndex);
    

    If you want to get the path of that given URL, you can also use a RE:

    string = string.match(/\/\/[^\/]+\/(.+)?/)[1];
    

    This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /.

提交回复
热议问题