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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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!!!