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
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) .
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With