Tuesday, February 19, 2013

JavaScript function to remove all spaces in a String using regular expression

Many a time it is needed to trim all the spaces from a text field like First Name, Last Name, Amount etc where Spaces " " are not allowed and which should be removed then its very useful to replace all the spaces in the text field or text area.

The following function can be used to replace all the spaces through the use of regular expression:

function trimString(field)
{
 return field.replace(/\s/g,"");
}

Example :

trimString (" Code - Zila  :  The -  Code - District  ");

returns : "Code-Zila:The-Code-District" 


How it works:

The function internally used javaScript replace function to find spaces " " using regular expression "\s" for space character and then replaces it with "".

The function call be called through the events : onClick() or onBlur()

Hope you would find it helpful.