There are regex matching methods on both RegExp objects and String objects in Javascript.
RegExp objects have the methods
- exec
- test
String objects have the methods
- match
- search
The exec and match methods are very similar:
/word/.exec("words");
//Result: ["word"]
"words".match(/word/);
//Result: ["word"]
/word/.exec("No match");
//Result: null
"No match".match(/word/);
//Result: null
/word/g.exec("word word");
//Result: ["word"]
"word word".match(/word/g);
//Result: ["word", "word"]
and the test and search are also very similar:
/word/.test("words");
//Result: true
"words".search(/word/);
//Result: 0
//Which can converted to a boolean:
"word".search(/word/) > -1;
//Result: true
/word/.test("No match");
//Result: false
"No match".search(/word/) > -1;
//Result: false
Is there a preference to use the methods on RegExp objects or on String objects?