String search into html
I'm trying to find some text in a long string but my code does not work, For Example:
Var result = “<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional/开发者_如何学C/EN html><head<title>Hey i am here</title>”
if (result.search('Hey i am here')== true) {
alert('found');
} else { alert('NOT found'); }
But This dont Works :( Please help
var
is lower case- Strings can be delimited with
"
or'
but not with“
, don't use curly quotes. - The
search
method expects a regular expression (although it will try to convert a string if it gets one) - If you want a simple string match, then
indexOf
is more efficient thensearch
. - Both
search
andindexOf
return the index of the first match (or-1
if it doesn't find one), not a boolean.
As an aside, that Doctype will trigger quirks mode, so never use it in a real HTML document.
var result = "<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN html><head<title>Hey i am here</title>"
if (result.indexOf("Hey i am here") >= 0) {
alert('found');
} else {
alert('NOT found');
}
I thinks you need to use an .indexOf function.
so your if statement would be
if (results.indexOf('Hey i am here') != -1) {
alert('found');
} else { alert('NOT found'); }
There are a lot of ways to do this: See here
Search
method returns the position of the match, or -1 if no match is found. Not true
or false
.
精彩评论