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 replace all spaces

Simple example code replace all white spaces with -:

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

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

    var out = myString.replace(/ /g,"")



JavaScript replace all spaces

Regex to replace multiple spaces with a single space

Just replace \s\s+ with ' ':

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


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

Your email address will not be published. Required fields are marked *