Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 525
Sharon S Avatar asked Jul 30 '13 04:07

Sharon S


People also ask

How do you remove whitespace at the end of a string?

The String. trim() method # You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string.

How can remove space from string in jquery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

What method removes only trailing Whitespaces from a string?

Use the . rstrip() method to remove whitespace and characters only from the end of a string.

How do you remove whitespace from the beginning and end of a string?

To remove whitespace characters from the beginning or from the end of a string only, you use the trimStart() or trimEnd() method.


2 Answers

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

like image 153
go-oleg Avatar answered Sep 30 '22 07:09

go-oleg


For some browsers you can use: str = str.trimRight(); or str = str.trimEnd();

If you want total browser coverage, use regex.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

like image 27
Marco Gaspari Avatar answered Sep 30 '22 08:09

Marco Gaspari