Many times I'm using the string match
function to know if a string matches a regular expression.
if(str.match(/{regex}/))
Is there any difference between this:
if (/{regex}/.test(str))
They seem to give the same result?
This question is related to
javascript
regex
performance
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
Source: Stackoverflow.com