开发者

How do you use the search method in javascript in an if statement?

开发者 https://www.devze.com 2023-01-22 11:11 出处:网络
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 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.


You can use regexes also:

if (/e/.test(str)) {
    ...
}


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.


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.


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

  • http://www.w3schools.com/jsref/jsref_search.asp

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 ...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号