How to Remove Whitespace Characters From the End of a JavaScript String?

Trim whitespace characters from the end of a string in JavaScript

To remove whitespace characters from the end of a string (which is different than removing only space characters), you can use any of the following methods:

Using String.prototype.trimEnd()

Introduced in ES10, you can use the String.prototype.trimEnd() method to remove whitespace characters from the end of a string.

Please note that the String.prototype.trimEnd() method returns a new string with stripped out whitespace characters from the right-most side of a given string. A new string is returned regardless of whether there is whitespace at the end of the string or not.

For example:

// ES10+
const str = ' foo, bar, baz.\r\n\t\v\f    ';
const newStr = str.trimEnd();

console.log(newStr); // ' foo, bar, baz.'
console.log(str); // ' foo, bar, baz.\r\n\t\v\f    '

Please be aware that for web compatibility reasons, the String.prototype.trimRight() method remains as an alias to the String.prototype.trimEnd() method. However, you should use String.prototype.trimEnd() wherever possible.

Using a Regular Expression

If you're unable to support ES10, you may use a simple regular expression to remove any number of whitespace characters from the end of a string. For example:

const str = ' foo, bar, baz.\r\n\t\v\f    ';
const newStr = str.replace(/\s*$/, '');

console.log(newStr); // ' foo, bar, baz.'
console.log(str); // ' foo, bar, baz.\r\n\t\v\f    '

The regular expression pattern does the following:

  • \s* — Matches any number of whitespace characters;
  • $ — Matches at only the end of the string.

How to Verify the Whitespace Characters are Removed?

To verify the new string has all the whitespace characters removed, you can use the String.prototype.includes() (or String.prototype.indexOf()) method like so:

// ES6+
newStr.includes('\r'); // false
newStr.includes('\n'); // false
// ...

Since the string has multiple instances of the space character, you can use the String.prototype.lastIndexOf() method to verify that the last space character in the new string is before the word "baz" (and not at the end of the string anymore):

newStr.lastIndexOf(' '); // 10

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.