Note that you pass the string to match . If we follow the documentation , new RegExp(test) will do this. Therefore, you should avoid the lines / and /gi and add the appropriate flags to the RegExp constructor: the default constructor does not add a global search ( g ) or case insensitive to case ( i ).
So the solution to your problem:
var str = "The rain in SPAIN stays mainly in the plain"; var test = "ain"; var res = str.match(new RegExp(test, "gi"));
This will return:
Array [ "ain", "AIN", "ain", "ain" ]
Note:
Form str.match(test, "gi"); only works in the Firefox browser, but is outdated and issues a console warning from Firefox 39 (see RGraham's comment).
TrapII
source share