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.
We used the String.trim method to get a copy of the string with the leading and trailing spaces removed. The trim method does not change the original string, instead it returns a new string stripped of any leading whitespace. Strings are immutable in JavaScript.
The first parameter is given a regular expression with a space character (” “) along with the global property. This will select every occurrence of space in the string and it can then be removed by using an empty string in the second parameter.
Sometimes, string returned from backend consists of either leading or trailing whitespace and in some case contains whitespaces at both ends So, we need to remove those leading & trailing whitespaces from string returned before displaying to end user/client system 1. Using trim () method – in selected browsers
Strings are immutable in JavaScript. If the string contains no leading or trailing spaces, the trim method returns a copy of the original string and does not throw an error. When the trim method is used on a string that contains leading or trailing spaces, the new string has a new length.
Use String#replace
with regex /\s+$/
and replacing text as empty string.
string.replace(/\s+$/, '')
console.log(
'-----' + ' test '.replace(/\s+$/, '') + '-----'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With