Javascript RegExp match: Bug or intent?


#1

I have noticed that strings in Codecombat do not support Javascript regex match. e.g.

var string = "hero error";
var regEx = new RegExp("er","g");
var matches = string.match(regEx); //this should return an array

fails with

string has no method match

Is this a bug, intended behaviour or am I missing something?

The behaviour “do for all matches” can be mimicked by

var match;
while (match = regEx.exec(string)) {
    doSomethingWith(match);
}

, however this raises a brown (warning?) box complaining about assingnment where expression is expected. This, however is perfectly OK and expected behaviour - the same as while(enemy = hero.findNearestEnemy()) {} which complains as well. Can the warning boxes be turned off (I’d be happy with the info exclamation mark only)


#2

Dunno about String.prototype.match, but as for your second question you could wrap the assignment with another set of parenthesis to silence the warnings:

 var match;
-while (match = regEx.exec(string)) {
+while ((match = regEx.exec(string))) {
     doSomethingWith(match);
 }

or by adding a JSHint directive at the top of the code to ignore those warnings.

/* jshint boss:true */