[caption id="attachment_612" align="aligncenter" width="1000"] Searching a string in Javascript[/caption]
exec() vs match() vs test() vs search() vs indexOf()
Is it all about speed??
What is the differences?
- test()
- Use test() whenever you want to know whether a pattern is found in a string (similar to the String.prototype.search() method); for more information (but slower execution) use the exec() method (similar to the String.prototype.match() method). As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.
- Syntax regexObj.test(str)
- Returns:True or False
- MDN definition of test()
- indexOf()
- Syntax: str.indexOf(searchValue[, fromIndex])
- Returns: True (0) or False (-1), and also a can search the entire string or can start from a point in the string using the fromIndex parameter.
- in indexOf Found == 0
in indexOf not Found == -1
FOUND indexOf !== -1
FOUND indexOf > -1if you want to say something is found != -1 is a safer equivalent because 0 could as be a NULL value
You can also say if Something is found it is > -1 because a found string is equal to 0 and that is greater than -1
- MDN definition of indexOf()
- match()
- Syntax: str.match(regexp)
- Returns An Array containing the matched results or null if there were no matches.
- MDN definition of match()
- search()
- Syntax: str.search(regexp)
- Returns: search()returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1
- MDN definition of search()
- exec()
- Syntax: regexObj.exec(str)
- Returns array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
- MDN definition of exec()