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?

7
  • 1
    try reversing the condition Commented Apr 28, 2013 at 6:03
  • 1
    search expects a regex, not a literal match Commented Apr 28, 2013 at 6:05
  • I've reverted ~ back to > -1 in my answer. Was that why you've unaccepted? Commented Apr 28, 2013 at 6:20
  • Please unaccept Chris' answer. He wants to delete it as it is incorrect. Commented Apr 28, 2013 at 15:08
  • @doniyor out of interest where are you getting the string http://www.google.de from? Commented Apr 28, 2013 at 15:38

2 Answers 2

9

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');   
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

works as expected, I used search and it broke my code when a user types \ indexOf fixes this bug and it produces the same return value as search

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.