Javascript 删除最后一个反斜杠后的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14462407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:51:52  来源:igfitidea点击:

Remove everything after last backslash

javascriptnode.jsregextypescriptnode-modules

提问by InGeek

var t = "\some\route\here"

var t = "\some\route\here"

I need "\some\route" from it.

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

Thank you.

谢谢你。

回答by Reinstate Monica Cellio

You need lastIndexOfand substr...

你需要lastIndexOfsubstr...

var t = "\some\route\here";
t = t.substr(0, t.lastIndexOf("\"));
alert(t);

Also, you need to double up \chars in strings as they are used for escaping special characters.

此外,您需要将\字符串中的字符加倍,因为它们用于转义特殊字符。

UpdateSince this is regularly proving useful for others, here's a snippet example...

更新由于这经常被证明对其他人有用,这里有一个片段示例......

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

回答by ic3b3rg

As stated in @Archer's answer, you need to double up on the backslashes. I suggest using regex replace to get the string you want:

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

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

回答by isuru

Using JavaScript you can simply achieve this. Remove everything after last "_" occurance.

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

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