Hi guys I'm trying to code this function in javascript to alert the ( text ) that matches the string that im looking for so If the string is (number 5656) the code will look for the number that exists after space after the word (number) and alert it to the client so the problem is that I need the Code to print each number alone like if the string Is (number 5656 number 4646) i want it to alert all the number each number alone so I tried this
({ data: { text } }) => { var rx = new RegExp( '\\s(\\w+)' ); var txt = text; var mtc = []; while( (match = rx.exec( txt )) != null ) { alert( match[1] ); mtc.push(match[1]); } })
And it gives infinite alert for the number after the string not just two times
Currently, you're always finding the same occurrence. You can add the global flag or sticky flag to store the position of the last occurrence and to search for the next occurrence:
({ data: { text } }) => { var rx = new RegExp( '\\s(\\w+)', 'g' ); var txt = text; var mtc = []; while( (match = rx.exec( txt )) != null ) { alert( match[1] ); mtc.push(match[1]); } }
JavaScript
RegExpobjects are stateful when they have the global or sticky flags set (e.g./foo/gor/foo/y).
const f = ({ data: { text } }) => { var rx = new RegExp( '\\s(\\w+)', 'g' ); var txt = text; var mtc = []; while( (match = rx.exec( txt )) != null ) { alert( match[1] ); mtc.push(match[1]); } };
f({ data: { text: 'number 5656 number 4646' } });
You can use String.match() to search for groups of 1 or more digits (\d+) with the global flag (g). Then loop over the matches and alert them.
let input = 'number 5656 number 4646';
let matches = input.match(/(\d+)/g);
matches.forEach(m => alert(m));
Since this is clearly related to your other question about tesseract.js, I'm just going to add this full example :
Tesseract.recognize(image,lang).then(result => {
let matches = result.data.text.match(/(\d+)/g);
matches.forEach(m => alert(m));
});