First, String#search
expects a regex, not a string. If it encounters a non-regex, it tries to convert it into a regex via new RegExp(patt)
. In case of a string, it treats the string as a regex pattern. This means that your search will behave unexpectedly (match more than desired, match less than desired or even throw a syntax error, if the string is not a valid regex) if the search string contains characters that have a special meaning in regular expressions. Use indexOf
instead.
Second, search
and indexOf
return the position of the first match, or -1 if no match has been found. This means that if the return value is less than zero, nothing has been found. If the return value is zero, the match was made at the beginning of the string.
Also note there is a handy shortcut for x != -1
: the bitwise negation ~x
if("http://www.google.de".indexOf("http://") > -1){
alert('with http');
} else {
alert('no http');
}