0

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

Fuxi
  • 329
  • 2
  • 6
  • 15

2 Answers2

2

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();
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Try this to replicate a right trim:

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