2013-01-22 103 views
18

var t = "\some\route\here"删除最后一个反斜杠后的所有内容

我需要“\ some \ route”。

谢谢。

+0

看吧: http://stackoverflow.com/questions/6764435/jquery-split-after-last-slash –

+2

它不能使用jQuery'来完成:P'。 –

+0

[MDN - 'String.prototype.lastIndexOf()'](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) – KyleMit

回答

40

你需要lastIndexOfsubstr ...

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

+0

Thank You。How do I双。我试过这个t.replace(“\\”,“\\\\”)它没有用 – INgeek

+1

你只需要在代码中直接设置字符串值就可以了,就像上面的例子。如果你从其他地方得到它(例如URL),那么不要担心它:) – Archer

+0

t.replace(/ \\/g,“\\\\”)没有工作 – INgeek

5

项记载@射手的答案,你需要在翻倍反斜杠。我建议使用正则表达式替换来得到你想要的字符串:

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

谢谢你,仍然无法找到如何加倍反斜杠 – INgeek

+0

你需要在字符串本身内做到这一点。在JavaScript中,“\”是转义字符,所以“\ k”(例如)被解析为“k”。 – ic3b3rg

+0

非常感谢你 – INgeek

1

使用JavaScript,你可以简单地实现这一目标。在最后一次“_”发生后,删除所有内容。

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

isuru,这是不是已经很好地覆盖了现有的答案? – KyleMit

+0

@KyleMit你看不到?他更新了他以前的答案。 – isuru

+0

要添加*甚至更多*信息,但即使版本日期[2013年1月22日](https://stackoverflow.com/posts/14462451/revisions)包含't = t.substr(0,t.lastIndexOf(“ \\“));'这与您的答案相同 – KyleMit

相关问题