How to loop all the elements that match the regex?

前端 未结 8 1526
囚心锁ツ
囚心锁ツ 2020-12-02 18:27

Here is the case: I want to find the elements which match the regex...

targetText = \"SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext\"

8条回答
  •  一整个雨季
    2020-12-02 19:00

    I kept getting infinite loops while following the advice above, for example:

    var reg = /e(.*?)e/g;
    var result;
    while((result = reg.exec(targetText)) !== null) {
        doSomethingWith(result);
    }
    

    The object that was assigned to result each time was:

    ["", "", index: 50, input: "target text", groups: undefined]
    

    So in my case I edited the above code to:

    const reg = /e(.*?)e/g;
    let result = reg.exec(targetText);
    while(result[0] !== "") {
        doSomethingWith(result);
        result = reg.exec(targetText);
    }
    

提交回复
热议问题