最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to loop all the elements that match the regex? - Stack Overflow

programmeradmin8浏览0评论

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

targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"

and I use the regex in javascript like this

reg = new RegExp(/e(.*?)e/g);   
var result = reg.exec(targetText);

and I only get the first one, but not the follow.... I can get the T1 only, but not T2, T3 ... ...

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

targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"

and I use the regex in javascript like this

reg = new RegExp(/e(.*?)e/g);   
var result = reg.exec(targetText);

and I only get the first one, but not the follow.... I can get the T1 only, but not T2, T3 ... ...

Share Improve this question asked Aug 3, 2009 at 12:22 DNB5brimsDNB5brims 30.5k50 gold badges133 silver badges203 bronze badges 1
  • 3 Can anyone suggest a for loop way to do it? – DNB5brims Commented Aug 3, 2009 at 12:34
Add a comment  | 

9 Answers 9

Reset to default 92

function doSomethingWith(result) {
  console.log(result)
}

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

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].
    } 
    

Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.

reg = new RegExp(/e(.*?)e/);   
var matches = targetText.match(reg);

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);
}
targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"    
reg = new RegExp(/e(.*?)e/g);   
var result;
while (result = reg.exec(targetText))
{
    ...
}

You could also use the String.replace method to loop through all elements.

result = [];
 // Just get all numbers
"SomeT1extSomeT2extSomeT3ext".replace(/(\d+?)/g, function(wholeMatch, num) {
  // act here or after the loop...
  console.log(result.push(num));
  return wholeMatch;
});
console.log(result); // ['1', '2', '3']

Greetings

I did this in a console session (Chrome).

> let reg = /[aeiou]/g;
undefined
> let text = "autoeciously";
undefined
> matches = text.matches(reg);
(7) ["a", "u", "o", "e", "i", "o", "u"]
> matches.forEach(x =>console.log(x));
a
u
o
e
i
o
u

Although @tvanfosson suggested in his answer, I'm adding the modified version for someone who only needs to get all matchings.

var targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext";
var reg = /e(.*?)e/g;
var ss = targetText.match(reg); // ss = "eT1e,eT2e,eT3e,eT4e,eT5e,eT6e"

I was actually dealing with this issue. I prefer Lambda functions for about everything.

reg = /e(.*?)e/gm;   
targetText.match(reg).forEach(element => console.log(element));
发布评论

评论列表(0)

  1. 暂无评论