How to get the last part of a string in JavaScript?

后端 未结 6 1375
野趣味
野趣味 2020-12-23 16:22

My url will look like this:

http://www.example.com/category/action

How can I get the word \"action\". This last part of the url (after the last forward slash

6条回答
  •  感情败类
    2020-12-23 16:32

    str.substring(str.lastIndexOf("/") + 1)
    

    Though if your URL could contain a query or fragment, you might want to do

    var end = str.lastIndexOf("#");
    if (end >= 0) { str = str.substring(0, end); }
    end = str.lastIndexOf("?");
    if (end >= 0) { str = str.substring(0, end); }
    

    first to make sure you have a URL with the path at the end.

提交回复
热议问题