5

Suppose I need a single value from a string, say a version number. Should I use exec() or match()?

Snippet1

res1 = /(\d+\.\d+)/.exec(some_string)[0];

vs

Snippet2

res1 = some_string.match(/\d+\.\d+/)[0];

which is better?

Ariel
  • 25,995
  • 5
  • 59
  • 69
  • 1
    Duplicate I'm afraid, but it's got an excellent answer!: http://stackoverflow.com/questions/10940137/regex-test-v-s-string-match-to-know-if-a-string-matches-a-regular-expression – christopher Apr 07 '13 at 20:14
  • 1
    Don't use `RegExp.$0`, but the [`exec`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec) method: `/(\d+\.\d+)/.exec(some_string)[0];` (you should validate if `.exec` returns a non-`null` value, otherwise an error is raised (same applies to `.match`). – Rob W Apr 07 '13 at 20:15
  • 2
    @livingston_mechanical There's a crucial difference: `.exec` is a method of a `RegExp` instance, whereas `.match` is only defined for strings. Using `some_string.match` would throw an error if `some_string` is not a string. – Rob W Apr 07 '13 at 20:24
  • 1
    @livingston_mechanical You've updated your question to something different. What answer are you expecting? There's no difference except for what I mentioned in my previous comment (unless the global modifier (`/g`) is used in the regular expression, which is not the case). – Rob W Apr 07 '13 at 20:28
  • 1
    @Chris Cooney - http://jsperf.com/match-vs-exec-1 .... match is faster in this case! –  Apr 07 '13 at 20:52
  • You have "test" in your first line instead of "exec" – Daan Dec 04 '13 at 10:28

2 Answers2

3

You can measure the performance of your code using https://jsbench.me/.

llobet
  • 2,672
  • 23
  • 36
1

It'd use match because it can be kept on one line, but it's a matter of taste.

mzedeler
  • 4,177
  • 4
  • 28
  • 41