64

var t = "\some\route\here"

我需要它的“\ some \ route”。

谢谢你。

4

3 回答 3

117

你需要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);

于 2013-01-22T15:46:54.117 回答
12

正如@Archer 的回答中所述,您需要在反斜杠上加倍。我建议使用正则表达式替换来获取您想要的字符串:

var t = "\\some\\route\\here";
t = t.replace(/\\[^\\]+$/,"");
alert(t);
于 2013-01-22T15:57:33.007 回答
10

使用 JavaScript,您可以简单地实现这一点。在最后一次“_”出现后删除所有内容。

var newResult = t.substring(0, t.lastIndexOf("_") );
于 2017-01-06T07:47:45.060 回答