👉 I guess, this may also be useful: How to convert JSON data dynamically to HTML table using plain JavaScript
<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>
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
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 ☺.