views:

314

answers:

4

I've got myself a project where I have to determine if a string contains set string. Example: What I'm looking for "website.com" What is might look like "jsngsowebsite.comadfjubj"

So far my own endevours have yielded this:

titletxt = document.getElementById('title');
titlecheck=titletxt.IndexOf("website.com");

if (titlecheck>=0)
{
  return false;
}

Which doesn't seem to be doing the trick, any suggestions?

A: 

Javascript functions are case sensitive - indexOf not IndexOf

gnarf
+2  A: 
function text( el ) {
    return el.innerText ? el.innerText : el.textContent;
}

function contains( substring, string ) {
    return string.indexOf(substring)>=0
}

contains( 'suggestions', text( document.getElementsByTagName('body')[0] ) )

Replace 'suggestions' and document.getElements... with a string and a dom element reference.

titlecheck=titletxt.IndexOf("website.com");

That looks like you're trying to use the IndexOf ( lowercase the I ) on a DOM element which won't even have that method, the text is inside the textContent ( standard DOM property ) or innerText ( IE specific property ).

meder
the contains function should be >= 0 - but otherwise +1 for pointing out the innerText of a DOM element
gnarf
thanks - slipped my mind, though innerText is IE DOM specific.
meder
A: 

You could also use String.match(...)

title = document.getElementById('title');
titletxt = title.innerText ? title.innerText : title.textContent
titlecheck = titletxt.match("website.com");

 if (titlecheck != null ) {
   return false;
 }

String.match returns null if no match is found, and returns the search string("website.com") if a match is found

Brian Gianforcaro
A: 

You can use the indexOf() method:

title = "lalalawebsite.comkkk";

// indexOf returns -1 if the string 'website.com' isn't found in 'title' titlecheck = title.indexOf("website.com") > 0? "found": "not found";

alert(titlecheck);

Elieder