Right now your regular expression is matching str
followed by a single character from the range i
- one single i
, meaning it will match stri
. To match the variable i
, try the following:
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp('str' + i, 'g')); //gives null
};
Here we are creating a regular expression whose pattern contains the current value of the variable i
. As an example, if i
is 4 then the regular expression will be constructed as if you had simply given /str4/g
to str.match
.
EDIT
To reflect the edit made to the question, my new proposed solution is as follows:
var str = "helloWorld";
var regResult;
for (var i = 0; i < str.length; i++) {
regResult = str.match(new RegExp(str[i], 'g')); //gives null
};
This code differs from the above code in that it is reading the value i
from str
. For example if i
is 4 and str[4] = "h"
, then the regular expression will be constructed as if you had simply given the value of str[4]
to str.match
: str.match(/h/g)
.