Tuesday, June 25, 2013

Trim, Ltrim, Rtrim, FullTrim - trimming string functions in Javascript


JQuery 1.9+ have inbuilt functions for string trimming, but they aren't supported in many browsers, such as, IE 8, IE 9, etc., and so I refrain myself from using those function, and hence there is a need to have our custom function to perform this job!

Following are javascript functions for trimming strings: 

function StringTrim(inputText){return inputText.replace(/^\s+|\s+$/g, '');};

function StringLtrim(inputText){return inputText.replace(/^\s+/,'');};

function StringRtrim(inputText){return inputText.replace(/\s+$/,'');};

function StringFulltrim(inputText){return inputText.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};

Add them in javascript library of your application, and you can use them to trim strings in various ways, such as, left trim, right trim, trim, and full trim.

Hope this helps!

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman