Remove any spaces from the end of a string?

Answered
nick asked this question 6 months ago
nick on Mar 13 · Edited

In my JavaScript application, I need to take a string and remove any unnecessary spaces that may be at the end of it.

For example, this string:

"The dog goes bark.      "

Should be converted to a new version with the spaces removed:

"The dog goes bark."

Is there an easy, built-in way to do this in JavaScript?

3 suggested answers
timmy123 on Apr 9

trimRight() will work for you. It removes trailing spaces from your string.

0 replies
moon_man41 on Apr 9

JavaScript has a built-in trimEnd() method:

string.trimEnd()

Supported by all browsers besides Internet Explorer.

0 replies
softwareguy411 on Apr 9

Option 1:

Regular expression (supported by all browsers):

string.replace(/\s+$/, "")

This will remove any trailing spaces in your string.

Use it like this:

let string = "   My example string.   "
string = string.replace(/\s+$/, "");

// "   My example string."

Option 2:

Use the trimEnd() method (supported by all browsers besides IE):

string.trimEnd()
0 replies
Answered