var t = "\some\route\here"
我需要从这段代码中提取 "\some\route"。
谢谢。
var t = "\some\route\here"
我需要从这段代码中提取 "\some\route"。
谢谢。
lastIndexOf
和substr
...var t = "\\some\\route\\here";
t = t.substr(0, t.lastIndexOf("\\"));
alert(t);
此外,在字符串中需要将\
字符加倍,因为它们用于转义特殊字符。
更新 由于这经常对其他人有用,这里是一个代码片段示例...
// 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("_") );
:P
。 - Felix KlingString.prototype.lastIndexOf()
- KyleMit