Trimming whitespace from the END of a string only, with jQuery

Sharon S picture Sharon S · Jul 30, 2013 · Viewed 15.7k times · Source

I know of the jQuery $.trim() function, but what I need is a way to trim whitespace from the END of a string only, and NOT the beginning too.

So

  str ="     this is a string     ";

would become

  str ="     this is a string";

Any suggestions?

Thanks!

Answer

go-oleg picture go-oleg · Jul 30, 2013

You can use a regex:

str = str.replace(/\s*$/,"");

It says replace all whitespace at the end of the string with an empty string.

Breakdown:

  • \s* : Any number of spaces
  • $ : The end of the string

More on regular expressions:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions