Steven
Steven

Reputation: 13975

Javascript error regex not a function?

I found some code online (stackoverflow https://stackoverflow.com/a/5774234/150062) that does exactly what I need. But I can't seem to get it running. I get an error "'/(\\d+)\\s*(second|min|minute|hour)/g' is not a function (evaluating 'regex(s)')";

var timespanMillis = (function() {
  var tMillis = {
    second: 1000,
    min: 60 * 1000,
    minute: 60 * 1000,
    hour: 60 * 60 * 1000 // etc.
  };
  return function(s) {
    var regex = /(\d+)\s*(second|min|minute|hour)/g, ms=0, m, x;
    while (m = regex(s)) {
      x = Number(m[1]) * (tMillis[m[2]]||0);
      ms += x;
    }
    return x ? ms : NaN;
  };
})();

I've never heard of this regex() function either? Is it suppose to be something else?

Upvotes: 1

Views: 8934

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176906

i think

regex.match(value)//or regx.exec(value)

is function you are looking for

regex is a RegExp object, not a function. here listing of method and function of Regular Expressions methods and usage

if match is not working than tryout .test() method like this

var match = /sample/.test("Sample text")

or

var match = /s(amp)le/i.exec("Sample text")

Upvotes: 1

Esailija
Esailija

Reputation: 140230

This used to be possible, you can replace the call with exec for exact same mechanism:

m = regex.exec(s)

See http://whereswalden.com/2011/03/06/javascript-change-in-firefox-5-not-4-and-in-other-browsers-regular-expressions-cant-be-called-like-functions/

Upvotes: 4

Related Questions