19

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!

2 Answers 2

42

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

Sign up to request clarification or add additional context in comments.

1 Comment

It removes new lines as well
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.