Home

SiteMap

How to Remove Blank Space from a String using RegEx in JavaScript

← PrevNext →

The JavaScript replace() method can be used to replace value in a string with a given value. However, if the value that you are trying to replace occurs more than once in the string, for example whitespaces, the replace() alone will not work. Since this method will only replace the first occurrence of the value. In this case you can use a Regular Expression or RegEx to search and replace values in a string.

👉 I guess, this may also be useful: How to convert JSON data dynamically to HTML table using plain JavaScript
Convert JSON to Table in JavaScript

The Script using RegEx and replace() Method
<html>
<head>
    <title>Remove Space in a String using RegEx in JavaScript</title>
</head>

<body>
    <input type="text" id="oldCode" value="0WO 2038 SHO2" />
    <input type="button" value="Click it" onclick="javascript:removeSpaces()" />
    
    <p id="newCode"></p>
</body>

<script>
    function removeSpaces() {
        var oldCode = document.getElementById('oldCode');
        var str = oldCode.value;        // STORE TEXTBOX VALUE IN A STRING.

        var newCode = document.getElementById('newCode');
        newCode.innerHTML = str.replace(/ /g, "") + '    <i>(all whitespaces removed)</i>';
    }
</script>
</html>
Try it

I am using JavaScript replace() method here in the script. The method takes two parameters. In the first parameter, I have two forward slash (separated by a space), followed by the RegEx g modifier.

/ /g

The g stands for global and it performs a global search for spaces (there is a space between the two slashes).

The second parameter in the replace() method is just two doubles quotes, with no spaces. Therefore, the method finds every space in the string and replaces the whitespaces with no space.

👉 How to use the replace() method in jQuery to get the number from an Element’s ID
jQuery replace() method example

Similarly, you can replace the spaces with other characters. For example, if you want to add a - (hyphen) in place of space, you can simply do this,

newCode.innerHTML = str.replace(/ /g, "-");

That’s it. Thanks for reading 🙂.

← PreviousNext →