MaikoID MaikoID - 3 years ago 224
Javascript Question

How to capture group with regex Javascript?

greetings for all you Jedi that can properly work with JS, I unfortunately cannot.

I want to iterate in all matches of the respective string ' m10 m20 m30 xm40', except the xm40, and extract the numbers, 10, 20, 30:

' m10 m20 m30 xm40'.match(/\s+m(\d+)/g)


but this is what I get in chrome console:

' m10 m20 m30 xm40'.match(/\s+m(\d+)/g)
(3) [" m10", " m20", " m30"]


why is the 'm' being captured too? I just can't understand. I've tried a lot of combination without success. Any thoughts?

Bye!

Answer Source

Use RegExp.exec() function:

const regex = /\sm(\d+)/g;
const str = '  m10 m20 m30 xm40';
let result = [];

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }        
    result.push(+m[1]);
}

console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download