Where the regular expression pattern does the following:
*— Matches any number of space characters;
$— Matches at only the end of the string.
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.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.