JavaScript String Trim Function
JavaScript doesn’t natively support the string trim (removing leading and trailing spaces) function, but this function is quite useful and required from time to time.
Fortunately, you can do this as easily as by just single line of code using regular expression and can add support to all the string objects using the JavaScript prototyping. Here is a quick sample of how you can do this:
String.prototype.trim = function() { return this.replace(/^s+|s+$/g, ''); } |
String.prototype.trim = function() { return this.replace(/^s+|s+$/g, ''); }
Once this is done. You can use the trim function on any string variable in the Javascript. Here is a quick demo:
var myname = " Akbar "; alert(myname.trim()); |
var myname = " Akbar "; alert(myname.trim());
Is’t this slick
Tags: function, JavaScript, string, trim
This entry was posted
on Saturday, May 29th, 2010 at 10:59 am and is filed under JavaScript.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Feedback & Comments
No Responses