admin管理员组文章数量:1136424
Relative newcomer to Javascript and looking for a way to remove the last character of a string if it is a colon.
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?
Thanks
Relative newcomer to Javascript and looking for a way to remove the last character of a string if it is a colon.
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?
Thanks
Share Improve this question edited May 23, 2014 at 11:16 T J 43.1k13 gold badges86 silver badges142 bronze badges asked Sep 3, 2012 at 13:29 neilneil 1,3062 gold badges12 silver badges20 bronze badges3 Answers
Reset to default 143The 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
$
needs to be at the end of the regex to match EOL.
/:$/
本文标签: stringJavascript Remove last character if a colonStack Overflow
版权声明:本文标题:string - Javascript: Remove last character if a colon - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736965243a1957880.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论