InG*_*eek 33 javascript regex node.js node-modules typescript
var t = "\some\route\here"
我需要"\ some\route".
谢谢.
Arc*_*her 71
你需要lastIndexOf和substr...
var t = "\\some\\route\\here";
t = t.substr(0, t.lastIndexOf("\\"));
alert(t);
Run Code Online (Sandbox Code Playgroud)
此外,您需要将\字符串中的字符加倍,因为它们用于转义特殊字符.
更新 因为这经常证明对其他人有用,这里是一个片段示例...
// 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);Run Code Online (Sandbox Code Playgroud)
正如@Archer的答案所述,你需要加倍反斜杠.我建议使用正则表达式替换来获取你想要的字符串:
var t = "\\some\\route\\here";
t = t.replace(/\\[^\\]+$/,"");
alert(t);
Run Code Online (Sandbox Code Playgroud)
使用JavaScript,您可以轻松实现这一目标。删除最后一次出现“ _”之后的所有内容。
var newResult = t.substring(0, t.lastIndexOf("_") );
Run Code Online (Sandbox Code Playgroud)