How to Remove Spaces From the End of a JavaScript String?

To only remove space character(s) from the end of a string in JavaScript (which is different than removing whitespace characters), you can use a simple regular expression pattern like so:

/ *$/

Where the regular expression pattern does the following:

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

For example:

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

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

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 none at the end of the string anymore):

newStr.lastIndexOf(' '); // 10

Also, you can use the String.prototype.includes() (or String.prototype.indexOf()) method to verify that the new string has all the other whitespace characters preserved:

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

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