Javascript: only remove trailing spaces

Can someone help me on how to remove spaces in JavaScript. I want to keep leading spaces as is and remove only spaces.
EG: ' test 'becoming ' test'. It seems to be pretty simple, but I can't figure it out.

PS: I’m pretty sure that I can’t be the first to ask about this, but I can’t find the answer in SO. Also, I am looking for a solution for JavaScript. I do not use jQuery.

+4
source share
4 answers

Use with regex and replace the text with an empty string. String#replace /\s+$/

string.replace(/\s+$/, '')

console.log(
  '-----' + '    test    '.replace(/\s+$/, '') + '-----'
)
Run codeHide result
+9
source
"    test    ".replace(/\s+$/g, '');
+1
source

trimRight()

var x ="   test   "

x.trimRight()
0

There is a way that you can create a regular expression inside the replace method, for example str.replace (/ \ s + $ / g, ''), will remove all trailing spaces.

0
source

All Articles