trim() method for JavaScript

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

trim() method for JavaScript

Post 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.
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

Or the replace with 1 regex.

Code: Select all

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