Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  154] [ 4]  / answers: 1 / hits: 90648  / 12 Years ago, mon, september 3, 2012, 12:00:00

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


More From » string

 Answers
38

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

[#83268] Saturday, September 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;