Skip to content

Javascript: remove trailing spaces only

Can anyone help me on how to remove trailing spaces in JavaScript. I want to keep the leading spaces as is and only remove trailing spaces.
EG: ' test ' becomes ' test'. Seems like pretty simple but I can’t figure it out.

PS: I am pretty sure I can’t be the first one to ask this but I can’t find an answer in SO. Also, I am looking for JavaScript solution. I am not using jQuery.


Use String#replace with regex /s+$/ and replacing text as empty string.

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

  '-----' + '    test    '.replace(/s+$/, '') + '-----'