Remove White Spaces from a String using jQuery

Users while entering text in textboxes may add extra whitespaces at the beginning or at the end of a textbox. jQuery provides the $.trim() function that removes, spaces, newline and tabs from the beginning and end of the string. Here’s how to use this function to remove white spaces in textboxes in your HTML or ASP.NET Pages

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Remove White Spaces in String (from DevCurry.com)</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$('input').blur(function () {
$(this).val(
$.trim($(this).val())
);
});
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" /><br /><br />
<
input id="Text2" type="text" />
</body>
</
html>

When a user enters some text in the textbox with some white space, then on the textbox blur event, the textbox value is fetched using $(this).val() and passed to the $.trim() function, which removes the white spaces at the beginning or end of the string.

Before (Observe White space at the beginning of string)

image

After (Textbox loses focus or user tabs out)

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.

2 comments:

gallee said...

hi,how will i use jquery in asp textbox,please help,im newbie.....

Suprotim Agarwal said...

gallee: I have plenty of articles on the same over here

http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=63