Removing all spaces from a string using Javascript

Asked

Viewed 8,331 times

2

I wonder if you have a way to remove all whitespace in a text using Javascript.

1 answer

8


You can use REGEX to perform such action, follow code example:

var strDefault = 'Te s te de remo ção de es pa ço s';

document.querySelector('.default').innerHTML = strDefault;

var str = strDefault.replace(/\s/g, '');

document.querySelector('.new').innerHTML = str;
<h1 class="default"></h1>

<br>

<h1 class="new"></h1>

I recommend using s to remove spaces as it will remove any type of character that represents a blank space, for example: '\t r n';

REGEX is very useful in cases where you need a dynamic pattern, it would be good to give a more thorough search on the subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.