jquery trimming empty spaces at the end of string

146 Views Asked by At

what is the easiest way to trim empty spaces from the end of a string in jquery/javascript? example: "my string " should return "my string"

thanks

2

There are 2 best solutions below

0
On

Try this to replicate a right trim:

var trimmedString = fullString.replace(/\s+$/,”");

3
On

jQuery's $.trim() will trim leading and trailing spaces from a string :

str = $.trim(str);

There's also the native trim() method that is supported in newer browsers, and there's a polyfill available on MDN for non-supporting browsers.

If for some reason you only want to trim trailing spaces, you can do something like :

String.prototype.trimTrail = function () {
    return this.replace(/\s+$/, '');
};

to be used as :

str = str.trimTrail();