Wednesday, May 4, 2011

JavaScript Trim Function Example

javascript trim function tutorial
In this tutorial we will learn how to remove white spaces from either sides of a string using javascript, usally all programming languages has built in function for trim but javascript don't have ... i am not getting in to any details... just give the code to do so... or in other words get the obvious stuff out of the way and let the code talk... the function mention below remove white space or any other char you specified.

Trim

removes white spaces from both side of the string
function trim(str, chars) {
 return ltrim(rtrim(str, chars), chars);
}

Right Trim

removes white spaces from right side of the string
function rtrim(str, chars) {
 chars = chars || "\\s";
 return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

Left Trim

removes white spaces from left side of the string
function ltrim(str, chars) {
 chars = chars || "\\s";
 return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

jQuery Trim

and last but not least jQuery if you it you have the power simply use the below mention function and you have a reason to smile :)
jQuery.trim(STRING_WITH_WHITE_SPACES);

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems