Skip to content

JavaScript replace all spaces | Example code

  • by

Use RegEx / /g with replace() method to Javascript replace all spaces. The flag g means global. It causes all matches to be replaced.

replaceSpace.replace(/ /g, "");

Pure Javascript, without regular expression:

var result = replaceSpacesText.split(" ").join("");

Javascript replaces all spaces

A simple example code replaces all white spaces with -:

<!DOCTYPE html>
<html>
<body>
  <script>
    let myString = "The dog      has a long   tail, and it     is RED!"

    var res = myString.replace(/ /g,"-")
    console.log(res)

    var out = myString.replace(/ /g,"")
    console.log(out)
  </script>

</body>
</html>

Output:

JavaScript replace all spaces

Regex to replace multiple spaces with a single space

Just replace \s\s+ with ' ':

  <script>
    let str = "The dog      has a long   tail, and it     is RED!"
    var res = str.replace(/\s\s+/g, ' ');

    console.log(res)
  </script>

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

Replace all spaces in a string with ‘+’

var str = 'a b c';
var replaced = str.split(' ').join('+');
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');

Do comment if you have any doubts or suggestions on this Js replace topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading