Page 1 of 1
Another JS RegExp issue / problem
Posted: Sat Apr 02, 2005 2:12 pm
by Chris Corbyn
Code: Select all
function example1(X) {
newVar = X.replace(/St(ring)/gi, "e;Prepend "e;+"e;$1"e;); //Should output "e;Prepend ring"e; and does! :-)
return newVar;
}
function example2(X) {
newVar = X.replace(/Some(String)/gi, example1("e;$1"e;)); //Should also output "e;Prepend ring"e; but doesn't! :-(
return newVar;
}
Any idea why the second function above fails? It only seems to fail if there's a search/replace in the function it calls. It just outputs "String" (The replace() in example1() doesn't replace anything. Test it and see
Thanks

Posted: Sat Apr 02, 2005 2:27 pm
by feyd
Javascript, like C, evaluates all dependant expressions first. In this case, example2() creates a new regexp object implicitly, and calls example1 with '$1' as an argument first.
Posted: Sat Apr 02, 2005 3:14 pm
by Chris Corbyn
There's something new I didn't know.
Thanks very much

Posted: Sat Apr 02, 2005 3:41 pm
by Chris Corbyn
If anybody really cares an obvious workaround came to mind...
Code: Select all
function example1(X) {
newVar = X.replace(/St(ring)/gi, "e;Prepend "e;+"e;$1"e;); //Should output "e;Prepend ring"e; and does! :-)
return newVar;
}
function example2(X) {
extracted = X.replace(/Some(String)/gi, "e;$1"e;);
newVar = X.replace(/Some(String)/gi, example1(extracted)); //Should also output "e;Prepend ring"e; but doesn't! :-(
return newVar;
}