Regex to replace multiple spaces with a single space

Viewed 624610

Given a string like:

"The dog      has a long   tail, and it     is RED!"

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

Goal:

"The dog has a long tail, and it is RED!"
25 Answers

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

string = string.replace(/\s\s+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:

str.replace( /  +/g, ' ' )       ->  380ms
str.replace( /\s\s+/g, ' ' )     ->  390ms
str.replace( / {2,}/g, ' ' )     ->  470ms
str.replace( / +/g, ' ' )        ->  790ms
str.replace( / +(?= )/g, ' ')    -> 3250ms

This is on Firefox, running 100k string replacements.

I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.

(Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)

var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

EDIT: If you wish to replace all kind of whitespace characters the most efficient way would be like that:

str = str.replace(/\s{2,}/g,' ');

This is one solution, though it will target all space characters:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

Edit: This is probably better since it targets a space followed by 1 or more spaces:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

Alternative method:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

I didn't use /\s+/ by itself since that replaces spaces that span 1 character multiple times and might be less efficient since it targets more than necessary.

I didn't deeply test any of these so lmk if there are bugs.

Also, if you're going to do string replacement remember to re-assign the variable/property to its own replacement, eg:

var string = 'foo'
string = string.replace('foo', '')

Using jQuery.prototype.text:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )

Also a possibility:

str.replace( /\s+/g, ' ' )
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

Or if you also want to replace tabs:

var replaced = string.replace(/\s+/g, " ");
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');
var text = `xxx  df dfvdfv  df    
                     dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');

result:

"xxx df dfvdfv df dfv"

I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.

@slightlytyler helped me in coming with the below approach.

const testStr = "I   LOVE    STACKOVERFLOW   LOL";

const removeSpaces = str  => {
  const chars = str.split('');
  const nextChars = chars.reduce(
    (acc, c) => {
      if (c === ' ') {
        const lastChar = acc[acc.length - 1];
        if (lastChar === ' ') {
          return acc;
        }
      }
      return [...acc, c];
    },
    [],
  );
  const nextStr = nextChars.join('');
  return nextStr
};

console.log(removeSpaces(testStr));

For more control you can use the replace callback to handle the value.

value = "tags:HUNT  tags:HUNT         tags:HUNT  tags:HUNT"
value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
//"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"

This script removes any white space (multiple spaces, tabs, returns, etc) between words and trims:

// Trims & replaces any wihtespacing to single space between words
String.prototype.clearExtraSpace = function(){
  var _trimLeft  = /^\s+/,
      _trimRight = /\s+$/,
      _multiple  = /\s+/g;

  return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
};

' mouse pointer touch '.replace(/^\s+|\s+$|(\s)+/g, "$1") should do the trick!

Using nodepad++ function, below regex works fine for me,

Find: {1}\K\s+
Replace:leave it empty

my name is Edelcio Junior. If you want to prevent 2 or more white spaces, here it is a good solution to you:

<label">Name</label>
<input type="text" name="YourInputName">

<script>
  var field = document.querySelector('[name="YourInputName"]');

  field.addEventListener('keyup', function (event) {
    var userName = field.value;
    userName = userName.replace(/\s{2,}/g, ' ');
    field.value = userName;
  });
</script>

  var field = document.querySelector('[name="YourInputName"]');

  field.addEventListener('keyup', function (event) {
    var userName = field.value;
    userName = userName.replace(/\s{2,}/g, ' ');
    field.value = userName;
  });
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <title>Your-title</title>
            <meta charset="utf-8">
          </head>
          <body>
            <form>
               <label>Name</label>
               <input type="text" name="YourInputName">
            </form>
          </body>
        </html>

let nameCorrection = function (str) {
  let strPerfect = str.replace(/\s+/g, " ").trim();
  let strSmall = strPerfect.toLowerCase();
  let arrSmall = strSmall.split(" ");
  let arrCapital = [];
  for (let x of arrSmall.values()) {
    arrCapital.push(x[0].toUpperCase() + x.slice(1));
  }

  let result = arrCapital.join(" ");
  console.log(result);
};
nameCorrection("Pradeep kumar dHital");

def removeblanks(text): return re.sub(r'\s\s+'," ",text) I was working on a large textual data with a lot of duplicate spaces. The above RE worked for me. All the duplicate blank spaces were replaced by a single space.

Related