Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: remove trailing spaces only

Tags:

javascript

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.

like image 379
user1 Avatar asked Jun 16 '16 16:06

user1


People also ask

How to remove leading and trailing spaces from a string in JavaScript?

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.

How do I remove space from a string 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.

How to remove leading&trailing whitespace from string returned from backend?

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

What happens when you trim a string in JavaScript?

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.


1 Answers

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

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

console.log(
  '-----' + '    test    '.replace(/\s+$/, '') + '-----'
)
like image 167
Pranav C Balan Avatar answered Oct 31 '22 02:10

Pranav C Balan