-1

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

blackriderws
  • 833
  • 2
  • 9
  • 14

3 Answers3

1
  1. var is lower case
  2. Strings can be delimited with " or ' but not with , don't use curly quotes.
  3. The search method expects a regular expression (although it will try to convert a string if it gets one)
  4. If you want a simple string match, then indexOf is more efficient then search.
  5. Both search and indexOf 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'); 
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Search method returns the position of the match, or -1 if no match is found. Not true or false.

VIK
  • 689
  • 2
  • 9
  • 20
0

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

Community
  • 1
  • 1
Brian Hoover
  • 7,861
  • 2
  • 28
  • 41