I\'m new to JavaScript and have a question about regular expressions. I have the following code:
var patt3=new RegExp(/(July|August)\\s+\\d{1,2}(\\s|,)\\d{4}
The crucial difference is that the string.match
method is defined to have a different behavior if the regex patter is global or not.
If the pattern is global, an array with all the matches. In your case you there is only one match but you can see the difference with an example like
let matches = "aaaa".match(/a(a)/g);
console.log(matches) // returns ["aa", "aa"]
If the pattern is not global, however, the method return an array corresponding to the first match found. The array contains the full matched string in the first position and the captures in the other positions. The captures are the bits of the regex delimited by parenthesis. Again, you can see the difference with that example:
"aaaa".match(/a(a)/g); // returns ["aa", "a"]
Finally, I would just like to point out some minor issues with your code.
First of all, you don't need to use the new Regexp
constructor here. Just use the regex literal directly
var patt3 = /(July|August)\s+\d{1,2}(\s|,)\d{4}/g
Secondly, don't blindly "toString" things. In your case you are applying that method to an array and that's why you get your weird results.
Finally, learn to use the developer tools, including the debugger and console.log. Its much better than abusing document.write and alert in terms of expressiveness and productivity.
console.write(match3)