Page 1 of 1

[SOLVED]trim RegExp

Posted: Mon Oct 30, 2006 2:36 am
by JellyFish
What would the regular expresion look like that would select all the spaces from the sides of a string.

Code: Select all

var element = "               hello this and that             ";
element.replace(regExp, "");  // returns "hello this and that";
what would regExp be?

Posted: Mon Oct 30, 2006 4:31 am
by Chris Corbyn

Code: Select all

//Define a new trim() method for String types
if (!"".trim)
{
    String.prototype.trim = function()
    {
        return this.replace(/^\s+/, "").replace(/\s+$/, "");
    }
}

Code: Select all

var myString = "   this has space to trim  ";
var trimmedString = myString.trim();

alert(trimmedString);

Posted: Mon Oct 30, 2006 5:13 am
by theYinYeti
What about /^\s*|\s*$/ ?

Yves.

Posted: Mon Oct 30, 2006 6:00 am
by Chris Corbyn
theYinYeti wrote:What about /^\s*|\s*$/ ?

Yves.
Should work :) Might need the "g" modifier o it replaces all occurences. /^\s*|\s*$/g

Posted: Mon Oct 30, 2006 6:47 am
by theYinYeti
Yes, you're right (in case there's blank in the start and in the end). Besides, I'd also replace * with + because there's no need to do a replacement from no space to no space (useless), hence the final RE: /^\s+|\s+$/g

Yves.

Posted: Mon Oct 30, 2006 5:44 pm
by JellyFish
Lol, I just wrote

Code: Select all

claus = claus.replace(/(^(\s)(\s){0,})?((\s){0,}(\s$))?/g, "");
Seems to work...

I need to get used to creating objects. I barely use them, I don't know if that's a good thing or what. Need to get the concept of the structuring of objects down.

This is good stuff though. Thanks for all the great replies guys. :D