0

I've found an interesting problem not answered here as far as I know. I have a regex object which I use to make replacements inside a string. The problem is that if I want to stop further replacements because I've found a specific string, I can't do so. The "break" statement obviously is not working because this is nor a loop neither a switch-case.

If I use "return" the replaces will continue. I can use the "incomplete" variable (see example below) at the head of the function to prevent further replacements but checkings will go on, it will be evaluated as many times as the regex is matched, which is not needed.

Is there a way to completely stop this function's replacements?

Thanks.

Example:

var regex = new RegExp("whatever", "g");
str = str.replace(regex, function(tot, group1) {
    if (group1 == "i_wanna_stop_str") {
        incomplete = true;
        break; <-- not working
    } else {
        ... compute replacement ...
        return replacement;
    }
}
4

2 に答える 2

1

フラグが見つかったら元のものに置き換えます。

var regex = new RegExp("whatever", "g");
str = str.replace(regex, function(tot, group1) {
    if (group1 == "i_wanna_stop_str") {
        incomplete = true;
        break; <-- not working
    } else {
        if (incomplete) {
            replacement = <captured original>;
        } 
        else {
            ... compute replacement ...
        }
        return replacement;
    }
}
于 2013-04-24T11:32:19.970 に答える
0

置換する正規表現が見つかったときに置換をループし、かつそれがストッパー文字列の前に見つかった場合

コードで:

var str = " blah blah whatever blah blah whatever i_wanna_stop_str blah blah whatever";
var stopStr = "i_wanna_stop_str";
var searchStr = "whatever";
while (str.indexOf(searchStr) != -1 && str.indexOf(searchStr) < str.indexOf(stopStr)) {
    str = str.replace(/whatever/, "some");
} 
于 2013-04-24T11:41:25.237 に答える