Niezrozumiałe działanie wyrażenia regularnego

0

Cześć!
Staram się zrobić prostą funkcję przyjmującą string jako argument, a zwracającą część stringa, która przejdzie test RegEx. Po wprowadzeniu "abba" do funkcji, na wyjściu powinienem otrzymać tę samą wartość, a zwrócony jest string "ab". Czy ktoś jest w stanie wytłumaczyć mi, dlaczego tak się dzieje? Poniżej kod:

const checkingRegex = str => {

    const regex = /[a-zA-Z0-9]/g;
    let finalStr = "";

    for (let i = 0; i < str.length; i++) {
        if (regex.test(str[i]))
            finalStr += str[i];
    };

    return finalStr;

}

checkingRegex("abba")
2

Za https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

1

Żeby naprawić Twoją funkcję musiałbyś skasować flagę g z regexa.

const regex = /[a-zA-Z0-9]/;

ewentualnie resetować lastIndex wewnątrz pętli

for (let i = 0; i < str.length; i++) {
    if (regex.test(str[i]))
        finalStr += str[i];

    regex.lastIndex = 0;
}
0

Dzięki za pomoc!

1 użytkowników online, w tym zalogowanych: 0, gości: 1