Another JS RegExp issue / problem

JavaScript and client side scripting.

Moderator: General Moderators

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

Another JS RegExp issue / problem

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

There's something new I didn't know.

Thanks very much ;-)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

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