[SOLVED]trim RegExp

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

[SOLVED]trim RegExp

Post 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?
Last edited by JellyFish on Thu Nov 02, 2006 3:41 pm, edited 1 time in total.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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);
User avatar
theYinYeti
Forum Newbie
Posts: 15
Joined: Thu Oct 26, 2006 3:33 pm
Location: France

Post by theYinYeti »

What about /^\s*|\s*$/ ?

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

Post 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
User avatar
theYinYeti
Forum Newbie
Posts: 15
Joined: Thu Oct 26, 2006 3:33 pm
Location: France

Post 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.
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post 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
Post Reply