tusharmath
tusharmath

Reputation: 10992

Regular expression for removing whitespaces

I have some text which looks like this -

"    tushar is a good      boy     "

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

The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -

"tushar is a good boy"

I am using the following code at the moment-

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

This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.

Upvotes: 24

Views: 113774

Answers (7)

Rohan-Santa
Rohan-Santa

Reputation: 11

This regex may be useful to remove the whitespaces

/^\s+|\s+$/g

Upvotes: 1

Joseph Myers
Joseph Myers

Reputation: 6552

This works nicely:

function normalizeWS(s) {
    s = s.match(/\S+/g);
    return s ? s.join(' ') : '';
}
  • trims leading whitespace
  • trims trailing whitespace
  • normalizes tabs, newlines, and multiple spaces to a single regular space

Upvotes: 8

DSurguy
DSurguy

Reputation: 385

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

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

JSFiddle

Upvotes: 5

cavaliercyber
cavaliercyber

Reputation: 234

try

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

first replace is delete leading and trailing spaces of a string.

Upvotes: -1

anubhava
anubhava

Reputation: 785146

This can be done in a single String#replace call:

var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// gives: "tushar is a good boy"

Upvotes: 37

Jacob
Jacob

Reputation: 78840

Try:

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

Upvotes: -1

Daniel A. White
Daniel A. White

Reputation: 190945

Try this:

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

If you don't have trim add this.

Trim string in JavaScript?

Upvotes: 4

Related Questions