[英]Javascript: Remove last character if a colon
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('/^\\\\:/');
我知道
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? 将在行的开始工作,但不知道如何交换
$
字符更改为行的结尾...任何人都可以纠正它?
Thanks 谢谢
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);
}
try simply with 试着简单地用
myString = myString.replace(/:$/, '');
this will remove :
when it is at the end of the string 这将删除
:
当它在字符串的末尾时
$
需要在正则表达式的末尾才能匹配EOL。
/:$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.