tags:

views:

47

answers:

4

I have an if statement that I want to execute if a certain variable does not have the <br/> element in it. How would you do this?

I tried

var str = "hello<br/>goodbye";
if( str.search("<br/>") == false) {
//execute certain code
}

but this did not work.

A: 

The search function returns an index. It will be >=0 if the value is found

if ( str.search("e") >= 0 ) { 
  // the string matches
}

search documentation

Your original question though mentions determining if the value does not have the <br/> element in it. Can you be a little more specific on this point. In particular what is the value: DOM element, string, etc ...

JaredPar
+2  A: 

The search() function returns the position that the match was found at (if any). If no match was found, it returns -1. So you want

var str = "hello";
if( str.search("e") <0) { //no match
//execute certain code
}

Also note that the search parameter is a regular expression; when you try to search for an HTML tag that may become relevant.

JacobM
ok, so what if I am trying to search for <br/> element?
chromedude
It works the exact same way. It just return s the starting position in the string of whatever you pass in as a parameter. The same code should work.
JohnFx
You should just be able to put `"<br/>"` where you currently have "e", but you might want to use a more sophisticated regex if, for example, you want to match `"<br />"` or `"<br style='clear:all' />"` and so forth.
JacobM
What's the advantage of `.search()` over `.test()`?
Peter Ajtai
@Peter: in this instance, there isn't one. Passing a string literal to *search()* implies a lack of understanding of the *search()* method.
Andy E
+3  A: 

You can use regexes also:

if (/e/.test(str)) {
    ...
}
Ned Batchelder
It's ironic that your post was down voted when it's actually more appropriate in this scenario than *search()*. *test()* works in a similar way to *search()*, except it returns a boolean for a successful match, rather than the matching substring's position. +1 to even it out.
Andy E
+1  A: 

Don't pass a string literal as the argument for search(). Any non-regular expression passed to search() will be used to create a regular expression and any "special" characters in it will lose their literal meaning. For example:

"Hello. Goodbye".search(".")

Will return 0, not 5 where the . character is. This is because . has a special meaning in a regular expression and will match any character except for a newline.

You actually require the indexOf() method, which does exactly the same thing but takes a string as its argument, and returns the position of the substring match within the string:

var str = "hello<br/>goodbye";
if(str.indexOf("<br/>") == -1) { // String not found
    //execute certain code
}

More information at the MDC documentation for search.

Andy E