简体   繁体   中英

simple javascript search() function is not working

I am trying to find some string part in another string. And I found a function called search() and tried this:

if("http://www.google.de".search("http://") > 0){
  alert('with http');    
} else {
  alert('no http');   
}

but it is giving me no http even if it has http:// part in it. here is the fiddle: http://jsfiddle.net/xXTuY/2/

can you please help me out?

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');   
}

"http://www.google.de".search("http://")返回0。0不小于0,因此您的条件为假。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM