Reputation: 1065
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.
Upvotes: 18
Views: 18710
Reputation: 21
Regex is worth knowing. But in case you don't, and don't want to use code you're not comfortable with, nor dive down that rabbit-hole for your current issue, here's a simple manual workaround:
/**
* @example
* trimEndSpaces('test \n '); // Returns: 'test \n'
* @param {string} str
* @returns {string}
*/
function trimEndSpaces(str) {
let i = str.length - 1;
// decrement index while character is a space
while (str[i] === ' ') {
i--;
}
// return string from 0 to non-space character
return str.slice(0, i + 1);
}
Upvotes: 2
Reputation: 29829
String trim methods have been added to ECMAScript spec in 2019 with wide browser support
You can use like this:
" test ".trimEnd() // " test"
Upvotes: 3
Reputation: 94
There is a way by which you can create a regex inside the replace method like str.replace(/\s+$/g,'') will remove all trailing spaces.
Upvotes: 0
Reputation: 115212
Use String#replace
with regex /\s+$/
and replacing text as empty string.
string.replace(/\s+$/, '')
console.log(
'-----' + ' test '.replace(/\s+$/, '') + '-----'
)
Upvotes: 30