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

后端 未结 6 1377
野趣味
野趣味 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条回答
  •  梦毁少年i
    2020-12-23 16:33

    Assuming there is no trailing slash, you could get it like this:

    var url = "http://www.mysite.com/category/action";
    var parts = url.split("/");
    alert(parts[parts.length-1]);
    

    However, if there can be a trailing slash, you could use the following:

    var url = "http://www.mysite.com/category/action/";
    var parts = url.split("/");
    if (parts[parts.length-1].length==0){
     alert(parts[parts.length-2]);
    }else{
      alert(parts[parts.length-1]);  
    }
    

提交回复
热议问题