Javascript: Remove last character if a colon

JavascriptStringReplace

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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);
}

Solution 2 - Javascript

try simply with

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

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

Solution 3 - Javascript

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

/:$/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneilView Question on Stackoverflow
Solution 1 - JavascriptGuffaView Answer on Stackoverflow
Solution 2 - JavascriptFabrizio CalderanView Answer on Stackoverflow
Solution 3 - JavascriptBen TaberView Answer on Stackoverflow