I have a string like that:
var str = 'aaaaaa, bbbbbb, ccccc, ddddddd, eeeeee ';
My goal is to delete the last space in the string. I would use,
str.split(0,1);
But if there is no space after the last character in the string, this will delete the last character of the string instead.
I would like to use
str.replace("regex",'');
I am beginner in RegEx, any help is appreciated.
Thank you very much.
When you need to remove all spaces at the end:
str.replace(/\s*$/,'');
When you need to remove one space at the end:
str.replace(/\s?$/,'');
\s
means not only space but space-like characters; for example tab.
If you use jQuery, you can use the trim
function also:
str = $.trim(str);
But trim
removes spaces not only at the end of the string, at the beginning also.
Do a google search for "javascript trim" and you will find many different solutions.
Here is a simple one:
trimmedstr = str.replace(/\s+$/, '');
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