Page 1 of 1

trim() method for JavaScript

Posted: Tue Aug 30, 2005 5:19 pm
by Chris Corbyn
Not sure this even qualifies as a snippet lol....

Code: Select all

String.prototype.trim = function()
{
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
}

//Example usage

var someString = '                     foo                 '; //Whitespace galore
var newString = someString.trim();
alert(newString);
If anyone knows how to make it return it's value back to the object that called it please say.... i.e. How to make "someString" automatically change by calling the method. I only recently learned how to create methods for built-in objects.

Posted: Thu Sep 15, 2005 11:54 am
by protokol
Or the replace with 1 regex.

Code: Select all

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