Javascript:如果是冒号,则删除最后一个字符

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

Javascript: Remove last character if a colon

javascriptstringreplace

提问by neil

Relative newcomer to Javascript and looking for a way to remove the last character of a string if it is a colon.

Javascript 的相对新手,正在寻找一种方法来删除字符串的最后一个字符(如果它是冒号)。

I know myString = myString.replace('/^\\:/');will work for the start of the line but not sure how to swap in the $character to change to the end of a line… can anybody correct it?

我知道myString = myString.replace('/^\\:/');行的开头会起作用,但不确定如何交换$字符以更改到行的末尾……有人可以更正吗?

Thanks

谢谢

回答by Guffa

The regular expression literal (/.../) should not be in a string. Correcting your code for removing the colon at the beginning of the string, you get:

正则表达式文字 ( /.../) 不应在字符串中。更正用于删除字符串开头的冒号的代码,您将得到:

myString = myString.replace(/^\:/, '');

To match the colon at the end of the string, put $after the colon instead of ^before it:

要匹配字符串末尾的冒号,请将其放在$冒号之后而不是^之前:

myString = myString.replace(/\:$/, '');

You can also do it using plain string operations:

您也可以使用纯字符串操作来实现:

if (myString.charAt(myString.length - 1) == ':') {
  myString = myString.substr(0, myString.length - 1);
}

回答by Fabrizio Calderan

try simply with

简单地尝试

myString = myString.replace(/:$/, '');

this will remove :when it is at the end of the string

这将:在它位于字符串末尾时删除

回答by Ben Taber

$needs to be at the end of the regex to match EOL.

$需要在正则表达式的末尾以匹配 EOL。

/:$/

/:$/