remove everything before the last occurrence of a character

前端 未结 5 1328
执念已碎
执念已碎 2020-12-13 23:34

I\'m trying to perform the following action on a string :

  • find the last occurrence of the character \"/\";
  • remove everything before that
5条回答
  •  悲&欢浪女
    2020-12-14 00:10

    Split the string into an array on / and .pop() off the last element. Note, that you will first need to strip off a trailing slash if there is one.

    var locationstring = window.location.pathname;
    // replace() the trailing / with nothing, split on the remaining /, and pop off the last one
    console.log(locationstring.replace(/\/$/, "").split('/').pop());
    

    If in the case of a URL like /path/stuff/here/ where you have the trailing /, if that case should return an empty string rather than here, modify the above to remove the .replace() from the call chain. I assumed you would want the last component regardless of a trailing slash, but may have incorrectly assumed.

    console.log(locationstring.split('/').pop());
    

提交回复
热议问题