How to loop all the elements that match the regex?

前端 未结 8 1521
囚心锁ツ
囚心锁ツ 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:03
    var reg = /e(.*?)e/g;
    var result;
    while((result = reg.exec(targetText)) !== null) {
        doSomethingWith(result);
    }
    
    0 讨论(0)
  • 2020-12-02 19:03

    Three approaches depending on what you want to do with it:

    • Loop through each match: .match

      targetText.match(/e(.*?)e/g).forEach((element) => {
         // Do something with each element
      });
      
    • Loop through and replace each match on the fly: .replace

      const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => {
        // Return the replacement leveraging the parameters.
      });
      
    • Loop through and do something on the fly: .exec

      const regex = /e(.*?)e/g;  // Must be declared outside the while expression, 
                                 // and must include the global "g" flag.
      
      let result;
      while(result = regex.exec(targetText)) {
        // Do something with result[0].
      } 
      
    0 讨论(0)
提交回复
热议问题