Skip to content Skip to sidebar Skip to footer

Removing Whitespace In JQuery

Right now my code is able to remove additional spaces, but it seems to mess up with new lines. If there are multiple breaks in the input, it removes all lines breaks. For example:

Solution 1:

You could use character classs to replace only spaces.

 output.val(input.val().replace(/[ ]{2,}/g,' '));

This would only find spaces, not tab characters and newlines. You could also put any combination of characters inside the brackets

 output.val(input.val().replace(/[ \t]{2,}/g,' '));

This would find all spaces and all tab characters.


Solution 2:

Just replace the space character (which represents itself in regex):

output.val(input.val().replace(/ {2,}/g, ' '));

Post a Comment for "Removing Whitespace In JQuery"