Javascript and regex: remove space after the last word in a string

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.


Seems you need a trimRight function. its not available until Javascript 1.8.1. Before that you can use prototyping techniques.

 String.prototype.trimRight=function(){return this.replace(/\s+$/,'');}
 // Now call it on any string.
 var a = "a string ";
 a = a.trimRight();

See more on Trim string in JavaScript? And the compatibility list


Do a google search for "javascript trim" and you will find many different solutions.

Here is a simple one:

trimmedstr = str.replace(/\s+$/, '');

You can use this code to remove a single trailing space:

.replace(/ $/, "");

To remove all trailing spaces:

.replace(/ +$/, "");

The $ matches the end of input in normal mode (it matches the end of a line in multiline mode).