2

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?

4

2 回答 2

8

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');   
}
于 2013-04-28T06:16:02.843 回答
1

"http://www.google.de".search("http://") returns 0. 0 is not less than 0 so your condition evaluates to false.

于 2013-04-28T06:05:37.320 回答