Skip to content
Advertisement

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.

Advertisement

Answer

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

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

console.log(
  '-----' + '    test    '.replace(/s+$/, '') + '-----'
)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement