JavaScript and client side scripting.
Moderator: General Moderators
JellyFish
DevNet Resident
Posts: 1361 Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA
Post
by JellyFish » Mon Oct 30, 2006 2:36 am
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.
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098 Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia
Post
by Chris Corbyn » Mon Oct 30, 2006 4:31 am
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);
theYinYeti
Forum Newbie
Posts: 15 Joined: Thu Oct 26, 2006 3:33 pm
Location: France
Post
by theYinYeti » Mon Oct 30, 2006 5:13 am
What about /^\s*|\s*$/ ?
Yves.
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098 Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia
Post
by Chris Corbyn » Mon Oct 30, 2006 6:00 am
theYinYeti wrote: What about /^\s*|\s*$/ ?
Yves.
Should work
Might need the "g" modifier o it replaces all occurences.
/^\s*|\s*$/g
theYinYeti
Forum Newbie
Posts: 15 Joined: Thu Oct 26, 2006 3:33 pm
Location: France
Post
by theYinYeti » Mon Oct 30, 2006 6:47 am
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.
JellyFish
DevNet Resident
Posts: 1361 Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA
Post
by JellyFish » Mon Oct 30, 2006 5:44 pm
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.