Remove all White Space using JavaScript

Here’s how to remove all whitespaces (leading, trailing and in between) in a textbox using JavaScript

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Remove Whitespaces using JavaScript by DevCurry.com</title>
<script type="text/javascript">
function removeWhitespaces() {
var txtbox = document.getElementById('txtOne');
txtbox.value = txtbox.value.replace(/\s/g, "");
}
</script>
</head>
<body>
<input id="txtOne" type="text" /><br />
<input id="btnRemoveWs" type="submit"
value="Remove Whitespaces" onclick="removeWhitespaces()" />
</body>
</html>


As you can see, we are using a simple regular expression \s/g which removes all whitespaces. The "g" stands for "global" which replaces all white space matches (front, trailing and in between).

Before

image

After

image

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Intellect said...

Wonderful blog.... nice info to know.... you also provide php coding?
thanks in advance for all valuable info to read....

Suprotim Agarwal said...

Sorry I would love to post PHP stuff on this blog, but unfortunately I am not a PHP guy! Hope I find someone who is interested in sharing his/her php knowledge on this blog.

Elisa said...

GREAT!!!! THANK YOU SOOOO MUCH!!!