Thursday, July 17, 2008

Trim(Remove Spaces) using JavaScript

Here is a simple JS function to trim the outer spaces inside a string.
Mainly used while validating User Inputs.

These are the three methods that we normally use

Method 1

Write a TrimString function using regular expression and call it when needed.

function TrimString(stringToTrim){
    return stringToTrim.replace(/^\s+|\s+$/g,"");

Now call it like

 var trimmedString = TrimString("    string to be trimmed         ");

If you alert trimmedString, you will get the value "string to be trimmed"

OR Method 2

If you want a more generic function for trimming, I would suggest taking a piece from Douglos Crockfords Remedial Javascript
Here we are extending the javascript String object with our own trim() function.
This is how we do that.
Declare the following prototype on the top of your page before any call to trim() occurs

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");

Now trim the string like

var str = "    string to be trimmed         ";
var trimmedString = str.trim();

OR Method 3

And if you are using jQuery, its much simpler.
jQuery natively has the trim() functionality and so just call it
No points for guessing that though! [:)]
<script type="text/javascript" src=""></script>
var str = "    string to be trimmed         ";
var trimmedString = jQuery.trim(str);

Related Posts :

0 comments on "Trim(Remove Spaces) using JavaScript"

Add your comment. Please don't spam!
Subscribe in a Reader

Post a Comment