Using a variable as a regular expression to find all matches inside a string
Often I have to use a value from a variable and not a fixed string inside a regular expression. For example if I wanted to iterate over the english alphabet and find the number of occurrences of each letter inside a string, I had to do something like the following:
1
2
3
var testString = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr.";
var matches = testString.match(/a/g).length;
// do this for all the remaining letters
the previous example would work and would find all occurrences of “a”.
Read the complete article