I'm practicing with regular expressions. I found a great answer here on StackOverflow: How do I retrieve all matches for a regular expression in JavaScript?
I copied the code from the checked answer and pasted it into an editor and then wrote my own function using it. So here's my JS file:
const regex = /[a-zA-Z]/g;
const _string = "++a+b+c++";
//The following is the loop from the StackOverflow user
var m;
do {
m = regex.exec(_string);
if (m) {
// Logging the results
console.log(m, "hello");
}
} while (m);
console.log("Separating top and bottom so it's easier to read");
// Now here is the function I wrote using that code
const match = str => {
let _matches;
do {
_matches = regex.exec(_string);
if (_matches) {
// Logging the results
console.log(_matches);
}
} while (_matches);
}
match(_string);
Here is my problem: when I run this code (it's a Repl.it) the results from the function that is first (so in this case, the loop from the stackoverflow user) do not include the first match return from the RegExp.prototype.exec() method. Here is my console output:
node v10.15.2 linux/amd64
[ 'b', index: 4, input: '++a+b+c++', groups: undefined ] 'hello'
[ 'c', index: 6, input: '++a+b+c++', groups: undefined ] 'hello'
Separating top and bottom so it's easier to read
[ 'a', index: 2, input: '++a+b+c++', groups: undefined ]
[ 'b', index: 4, input: '++a+b+c++', groups: undefined ]
[ 'c', index: 6, input: '++a+b+c++', groups: undefined ]
And if I switch the order of the loop and the function, the function will not return the first match and loop will return all three.
Any help would be much appreciated!