PDA

View Full Version : RegExp problem


snowtown
02-13-2003, 04:29 PM
Hi!

I'm having trouble replacing words in a string n times. The code I have is the following:

...
s.replace(RegExp(foo), bar);
...

Where foo (which is a variable) is to be replaced n times by the word bar (which also is a variable).

So my question is: Where, and how, do I put the n into the code above?


Thanks!

beetle
02-13-2003, 05:02 PM
You don't, you need a loop for that...

with a RegExp you can have it replace ALL or ONE, but no other quantity unless you hard code it, which is less than ideal :Dvar myString = "aaaaaaaa";
var foo = "a";
var bar = "b";

for ( var i = 0; i < 4; i++ )
{
myString = myString.replace( foo, bar );
}myString is now "bbbbaaaa"

Adam20002
02-13-2003, 05:05 PM
i *think* the way to get all instances of a string replaced is to specify to global attribute of the regular expression.

so the regular expression would be /some regEx/g


Adam

Adam20002
02-13-2003, 05:07 PM
scratch the above post beetle got there first lol Didnt realise u wanted a variable amount rather than all instances changed, my mistake.

Adam

snowtown
02-13-2003, 05:11 PM
Beetle; Yeah I suspected that I would have to come up with something else. Too bad it couldn't be done with RegExp though...

Thank you