I've got myself a project where I have to determine if a string contains a 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?
4 Answers 4
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 ).
2 Comments
Javascript functions are case sensitive - indexOf not IndexOf
Comments
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);
Comments
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