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 badges
Add a comment  | 

3 Answers 3

Reset to default 143

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

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

/:$/

本文标签: stringJavascript Remove last character if a colonStack Overflow