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, &quote;Prepend &quote;+&quote;$1&quote;); //Should output &quote;Prepend ring&quote; and does! :-)
    return newVar;
}

function example2(X) {
    newVar = X.replace(/Some(String)/gi, example1(&quote;$1&quote;)); //Should also output &quote;Prepend ring&quote; 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 :D

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, &quote;Prepend &quote;+&quote;$1&quote;); //Should output &quote;Prepend ring&quote; and does! :-)
    return newVar;
}

function example2(X) {
    extracted = X.replace(/Some(String)/gi, &quote;$1&quote;);
    newVar = X.replace(/Some(String)/gi, example1(extracted)); //Should also output &quote;Prepend ring&quote; but doesn't! :-(

    return newVar;
}