Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 497
neil Avatar asked Sep 03 '12 13:09

neil


People also ask

How do you get rid of the last character in a string JavaScript?

To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .

How do I remove the first and last character from a string in node JS?

To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str. slice(1, -1) . The slice method returns a new string containing the extracted section from the original string.


1 Answers

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); } 
like image 183
Guffa Avatar answered Oct 17 '22 20:10

Guffa