Home

SiteMap

How to Remove all whitespace from a string using RegEx in JavaScript

← PrevNext →

You can use the replace() method in JavaScript to replace value in a string with another 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 the "replace()" will only replace the first occurrence of the value. In this case you can use Regular Expression or RegEx to search and replace all whitespaces in a string.
Using RegEx and replace() Method

I have textbox with a default value. The value (string) has "multiple" whitespaces (or simply, spaces). I want to remove all the whitespaces at once.

<html>
<body>
    <input type="text" id="oldCode" value="0WO 2038 SHO2" />  <!--will remove all whitespaces from the value-->
    <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

➡️ Replace a string with another string in the URL

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 RegExp g modifier.

/ /g

➡️ RegExp refers to Regular Expression.

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.

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

← PreviousNext →