[javascript] Regex to replace multiple spaces with a single space

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!"

This question is related to javascript jquery regex

The answer is


I have this method, I call it the Derp method for lack of a better name.

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

Running it in JSPerf gives some surprising results.


I suggest

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

for just spaces
OR

string = string.replace(/(\s)+/g,"$1");

for turning multiple returns into a single return also.


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

result:

"xxx df dfvdfv df dfv"

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, ' ');
};

Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)

_x000D_
_x000D_
var str="The dog      has a long   tail, and it     is RED!";
var rule=/\s{1,}/g;

str = str.split(rule).join(" "); 

document.write(str);
_x000D_
_x000D_
_x000D_


var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');

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


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.)


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"

We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.

Add the text into some file say test

manjeet-laptop:Desktop manjeet$ cat test
"The dog      has a long   tail, and it     is RED!"

We can use the following regex to replace all white spaces with single space

manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"

Hope this serves the purpose


Comprehensive unencrypted answer for newbies et al.

This is for all of the dummies like me who test the scripts written by some of you guys which do not work.

The following 3 examples are the steps I took to remove special characters AND extra spaces on the following 3 websites (all of which work perfectly) {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} so I know that these work perfectly.

We have chained these together with over 50 at a time and NO problems.

// This removed special characters + 0-9 and allows for just letters (upper and LOWER case)

function NoDoublesPls1()
{
var str=document.getElementById("NoDoubles1");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces

function NoDoublesPls2()
{
var str=document.getElementById("NoDoubles2");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"");
}

// This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces // The .replace(/\s\s+/g, " ") at the end removes excessive spaces // when I used single quotes, it did not work.

function NoDoublesPls3()
{    var str=document.getElementById("NoDoubles3");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
}

::NEXT:: Save #3 as a .js // I called mine NoDoubles.js

::NEXT:: Include your JS into your page

 <script language="JavaScript" src="js/NoDoubles.js"></script>

Include this in your form field:: such as

<INPUT type="text" name="Name"
     onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

So that it looks like this

<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

This will remove special characters, allow for single spaces and remove extra spaces.


Try this to replace multiple spaces with a single space.

<script type="text/javascript">
    var myStr = "The dog      has a long   tail, and it     is RED!";
    alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'

    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
</script>

Read more @ Replacing Multiple Spaces with Single Space


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,' ');

A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

// NOTE the possible initial and trailing spaces
var str = "  The dog      has a long   tail, and it     is RED!  "

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

// str -> "The dog has a long tail, and it is RED !"

Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.


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, " ");

More robust:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}

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.

_x000D_
_x000D_
const testStr = "I   LOVE    STACKOVERFLOW   LOL";_x000D_
_x000D_
const removeSpaces = str  => {_x000D_
  const chars = str.split('');_x000D_
  const nextChars = chars.reduce(_x000D_
    (acc, c) => {_x000D_
      if (c === ' ') {_x000D_
        const lastChar = acc[acc.length - 1];_x000D_
        if (lastChar === ' ') {_x000D_
          return acc;_x000D_
        }_x000D_
      }_x000D_
      return [...acc, c];_x000D_
    },_x000D_
    [],_x000D_
  );_x000D_
  const nextStr = nextChars.join('');_x000D_
  return nextStr_x000D_
};_x000D_
_x000D_
console.log(removeSpaces(testStr));
_x000D_
_x000D_
_x000D_


Jquery has trim() function which basically turns something like this " FOo Bar " into "FOo Bar".

var string = "  My     String with  Multiple lines    ";
string.trim(); // output "My String with Multiple lines"

It is much more usefull because it is automatically removes empty spaces at the beginning and at the end of string as well. No regex needed.


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, ' ' )

I know that I am late to the party, but I discovered a nice solution.

Here it is:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');

is replace is not used, string = string.split(/\W+/);


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?