The search()
method executes a search for a match between a regular expression and this String object.
str.search(regexp)
regexp
obj
is passed, it is implicitly converted to a RegExp by using new RegExp(obj)
.search()
returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1.When you want to know whether a pattern is found in a string use search()
(similar to the regular expression test() method); for more information (but slower execution) use match() (similar to the regular expression exec() method).
search()
The following example logs a message which depends on the success of the test.
function testinput(re, str) { var midstring; if (str.search(re) != -1) { midstring = ' contains '; } else { midstring = ' does not contain '; } console.log(str + midstring + re); }
search()
was implemented incorrectly; when it was called with no parameters or with undefined, it would match against the string 'undefined', instead of matching against the empty string. This is fixed; now 'a'.search()
and 'a'.search(undefined)
correctly return 0.flags
argument is deprecated and throws a console warning (). This property is Gecko-only and will be removed in the future.Created by Mozilla Contributors and licensed under CC-BY-SA 2.5