简体   繁体   中英

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.

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"

Try this:

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

If you don't have trim add this.

Trim string in JavaScript?

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

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

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

JSFiddle

Try:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM