Javascript 正则表达式删除最后一个 / 如果它作为字符串中的最后一个字符存在

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

Regex to remove last / if it exists as the last character in the string

javascriptregex

提问by P.Brian.Mackey

I would like a regular expression or otherwise some method to remove the last character in a string if and only if that character is '/'. How can I do it?

我想要一个正则表达式或其他一些方法来删除字符串中的最后一个字符,当且仅当该字符是“/”时。我该怎么做?

回答by Rob W

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

$marks the end of a string. \/is a RegExp-escaped /. Combining both = Replace the /at the end of a line.

$标记字符串的结尾。\/是一个 RegExp 转义的/. 结合两者 =替换/行尾的 。

回答by Joe

Just to give an alternative:

只是提供一个替代方案:

var str="abc/";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // abc

var str="aabb";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // aabb

This plays off the fact the Number(true) === 1and Number(false) === 0

这不符合事实Number(true) === 1Number(false) === 0

回答by Dennis

var str = //something;
if(str[str.length-1] === "/") {
    str = str.substring(0, str.length-1);
}

回答by daiscog

var str = "example/";
str = str.replace(/\/$/, '');

回答by Larsenal

var t = "example/";
t.replace(/\/$/, ""));

回答by Chandrakant

This is not regex but could solve your problem

这不是正则表达式,但可以解决您的问题

var str = "abc/";

if(str.slice(-1) == "/"){
str = str.slice(0,-1)+ "";
}

回答by Metafr

$('#ssn1').keyup(function() {
      var val = this.value.replace(/\D/g, '');
      val = val.substr(0,9)
      val = val.substr(0,3)+'-'+val.substr(3,2)+'-'+val.substr(5,4)
      val = val.replace('--','').replace(/-$/g,'')
      this.value = val;
});