Remove everything after last backslash

前端 未结 3 714
滥情空心
滥情空心 2021-02-02 05:41

var t = \"\\some\\route\\here\"

I need \"\\some\\route\" from it.

Thank you.

3条回答
  •  不要未来只要你来
    2021-02-02 06:16

    You need lastIndexOf and substr...

    var t = "\\some\\route\\here";
    t = t.substr(0, t.lastIndexOf("\\"));
    alert(t);
    

    Also, you need to double up \ chars in strings as they are used for escaping special characters.

    Update Since this is regularly proving useful for others, here's a snippet example...

    // the original string
    var t = "\\some\\route\\here";
    
    // remove everything after the last backslash
    var afterWith = t.substr(0, t.lastIndexOf("\\") + 1);
    
    // remove everything after & including the last backslash
    var afterWithout = t.substr(0, t.lastIndexOf("\\"));
    
    // show the results
    console.log("before            : " + t);
    console.log("after (with \\)    : " + afterWith);
    console.log("after (without \\) : " + afterWithout);

提交回复
热议问题