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
// ...

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.