在 Javascript 中,如何检查字符串末尾是否包含 \(反斜杠),如果是,则将其删除?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10805442/
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-10-26 11:05:47  来源:igfitidea点击:

In Javascript how can I check if a string contains \ (backslash) at the end of it, and if so remove it?

javascript

提问by user1052933

Possible Duplicate:
Regex to remove last / if it exists as the last character in the string
Javascript: How to remove characters from end of string?

可能的重复:正则
表达式删除最后一个/如果它作为字符串中的最后一个字符存在
Javascript:如何从字符串的末尾删除字符?

In Javascript how can I check if a string contains \ (backslash) at the end of it, and if so remove it? Looking for a regex solution.

在 Javascript 中,如何检查字符串末尾是否包含 \(反斜杠),如果是,则将其删除?寻找正则表达式解决方案。

Appreciate your time and help.

感谢您的时间和帮助。

回答by Aren

if (myString.match(/\$/)) { 
  myString = myString.substring(0, myString.length - 1);
}

The Regex '\$' Will match an escaped character '\' followed by the end of line. If this is a match, it runs the substringmethod to get everything but the last character.

正则表达式 '\$' 将匹配转义字符 '\' 后跟行尾。如果这是匹配项,它将运行该substring方法以获取除最后一个字符之外的所有内容。

As pointed out, in this case this can be simplified to:

正如所指出的,在这种情况下,这可以简化为:

myString = myString.replace(/\$/, "");

(Thankyou @Lekensteyn for pointing it out)

(谢谢@Lekensteyn 指出)

I've left both answers up so one can see the methodology if removing the match is no longer the goal.

我已经留下了两个答案,所以如果删除匹配不再是目标,那么人们可以看到方法。

回答by David says reinstate Monica

I'd suggest:

我建议:

var string = 'abcd\';
if (string.charAt(string.length - 1) == '\'){
    // the \ is the last character, remove it
    string = string.substring(0, string.length - 1);
}

References:

参考: