1

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!

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thx, I had found a single line saying that for iterate over groups is better to user RegExp.exec without explaining why. And only your code worked properly! developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… I hate JS xD
1

Another way of getting just those digits would be to match against /\sm\d+/g first, and then return the results of mapping over those results and extracting the digits.

var m = str.match(/\sm\d+/g).map(el => el.match(/\d+/)[0]);

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.