Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  169] [ 7]  / answers: 1 / hits: 15755  / 8 Years ago, thu, june 16, 2016, 12:00:00

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.


More From » javascript

 Answers
40

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



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




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




[#61741] Tuesday, June 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;