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>
➡️ 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 Expressions.
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, "-");