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

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.

Also Read: Convert JSON Data Dynamically to HTML Table using 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.

Related Post: How to use the replace() Method in jQuery to Get the Number from an Element’s ID

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.

Previous - Change Label Text on Button Click using JavaScript or jQueryNext - Check if a Value Exists in an Array using Array includes() Method in JavaScript



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!