JS remove everything after the last occurrence of a character

前端 未结 9 1840
梦如初夏
梦如初夏 2020-12-11 16:47

Okay I have this

var URL = \"http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character\";
console.log(URL.subst         


        
相关标签:
9条回答
  • 2020-12-11 17:20

    Try utilizing .match() with RegExp /^\w+.*\d+\//

    var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
    var res = URL.match(/^\w+.*\d+\//)[0];
    document.body.textContent = res;

    0 讨论(0)
  • 2020-12-11 17:22
    var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
    
    console.log(URL.substring(0,URL.lastIndexOf('/')+1));
    //The +1 is to add the last slash
    
    0 讨论(0)
  • 2020-12-11 17:25

    Try an array based extraction like

    var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
    snippet.log(URL.split('/').slice(0, 5).join('/'));
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    0 讨论(0)
  • 2020-12-11 17:26

    Generic solution

    This is a generic function that also handles the edge case when the searched character or string (needle) is not found in the string we are searching in (haystack). It returns the original string in that case.

    function trimStringAfter(haystack, needle) {
      const lastIndex = haystack.lastIndexOf(needle)
      return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
    }
    
    console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
    console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
    console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
    console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
    console.log(trimStringAfter('abcd', '/')) // abcd

    0 讨论(0)
  • 2020-12-11 17:27

    Seems like a good case for a regular expression (can't believe no one has posted it yet):

    URL.replace(/[^\/]+$/,'')
    

    Removes all sequential non–forward slash characters to the end of the string (i.e. everything after the last /).

    0 讨论(0)
  • 2020-12-11 17:36

    Here you are:

    var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
    alert(URL.substring(0, URL.lastIndexOf("/") + 1));

    Hope this helps.

    0 讨论(0)
提交回复
热议问题