Friday, May 29, 2009

Trim function in javascript

Trim function in javascript

One important function which we miss very much while working with string object in javascript is the trim function. Not anymore. If you are using ASP.NET you can very well make use of “ValidatorTrim” function to trim both leading and trailing spaces. E.g. is shown below.

var testString = '   Test trail    text    ';
//Below code removes spaces before and after the word.
testString = ValidatorTrim(testString);

In the above e.g. ValidatorTrim removes the leading and trailing spaces in the “   Test text  ” string and returns “Test Text” as the string. So whenever you need to trim spaces in javascript then go ahead and use “ValidatorTrim” function to trim spaces.

If you keep a breakpoint on the ValidatorTrim function and step into the function you can see the following code.

function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

One can see from the above code that Regular Expression is used to pick out the text without the trailing and leading spaces. People who are not ASP.NET developers can very well implement the same logic and can have their own javascript trim function.

Try to know more

Sandeep

No comments:

Post a Comment

Please provide your valuable comments.