Remove everything after last backslash

旧街凉风 提交于 2019-12-03 08:13:05

问题


var t = "\some\route\here"

I need "\some\route" from it.

Thank you.


回答1:


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);



回答2:


As stated in @Archer's answer, you need to double up on the backslashes. I suggest using regex replace to get the string you want:

var t = "\\some\\route\\here";
t = t.replace(/\\[^\\]+$/,"");
alert(t);



回答3:


Using JavaScript you can simply achieve this. Remove everything after last "_" occurance.

var newResult = t.substring(0, t.lastIndexOf("_") );


来源:https://stackoverflow.com/questions/14462407/remove-everything-after-last-backslash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!