Regular expression to remove spaces

I have a text that looks like this:

" tushar is a good boy " 

Using javascript, I want to remove all the extra spaces in the string.

As a result, the line should not have many spaces, but only one. In addition, the beginning and the end must not have any spaces. So my final result should look like this:

 "tushar is a good boy" 

I am currently using the following code:

 str.replace(/(\s\s\s*)/g, ' ') 

This obviously fails because it does not care about white spaces at the beginning and end of the line.

+6
source share
6 answers

This can be done with a single call to String#replace :

 var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); // gives: "tushar is a good boy" 
+15
source

This works well:

 function normalizeWS(s) { s = s.match(/\S+/g); return s ? s.join(' ') : ''; } 
  • separates leading spaces
  • trims trailing spaces
  • normalizes tabs, newlines and multiple spaces into one regular space
+5
source

Try the following:

 str.replace(/\s+/g, ' ').trim() 

If you don't have trim , add this.

Javascript trim string?

+4
source

Since everyone complains about .trim() , you can use the following:

str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');

Jsfiddle

+2
source

Try:

 str.replace(/^\s+|\s+$/, '') .replace(/\s+/, ' '); 
-1
source

to try

 var str = " tushar is a good boy "; str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' '); 

the first substitution is to remove the leading and trailing spaces of the line.

-1
source

Source: https://habr.com/ru/post/951058/


All Articles