【发布时间】:2013-01-22 15:44:35
【问题描述】:
var t = "\some\route\here"
我需要它的“\some\route”。
谢谢。
【问题讨论】:
-
不能用 jQuery
:P.
标签: javascript node.js regex typescript node-modules
var t = "\some\route\here"
我需要它的“\some\route”。
谢谢。
【问题讨论】:
:P.
标签: javascript node.js regex typescript node-modules
你需要lastIndexOf和substr...
var t = "\\some\\route\\here";
t = t.substr(0, t.lastIndexOf("\\"));
alert(t);
此外,您需要将字符串中的 \ 字符加倍,因为它们用于转义特殊字符。
更新 由于这经常被证明对其他人有用,因此这里有一个 sn-p 示例...
// 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);
【讨论】:
正如@Archer 的回答中所述,您需要在反斜杠上加倍。我建议使用正则表达式替换来获取您想要的字符串:
var t = "\\some\\route\\here";
t = t.replace(/\\[^\\]+$/,"");
alert(t);
【讨论】:
使用 JavaScript,您可以简单地实现这一点。删除最后一次“_”出现后的所有内容。
var newResult = t.substring(0, t.lastIndexOf("_") );
【讨论】:
t = t.substr(0, t.lastIndexOf("\\"));,这与您的答案相同