Answered
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?
trimRight()
will work for you. It removes trailing spaces from your string.
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()