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
What is might look like jsngsowebsiteadfjubj
So far my own endevours have yielded this:
titletxt = document.getElementById('title');
titlecheck=titletxt.IndexOf("website");
if (titlecheck>=0) {
return false;
}
Which doesn't seem to be doing the trick, any suggestions?
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.
What is might look like jsngsowebsite.adfjubj
So far my own endevours have yielded this:
titletxt = document.getElementById('title');
titlecheck=titletxt.IndexOf("website.");
if (titlecheck>=0) {
return false;
}
Which doesn't seem to be doing the trick, any suggestions?
Share Improve this question edited Oct 19, 2020 at 12:28 Alex 1,5801 gold badge15 silver badges27 bronze badges asked Aug 22, 2009 at 21:56 VikingGoatVikingGoat 4774 gold badges9 silver badges30 bronze badges4 Answers
Reset to default 4function 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.");
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 ).
Javascript functions are case sensitive - indexOf
not IndexOf
You can use the indexOf()
method:
title = "lalalawebsite.kkk";
indexOf
returns -1
if the string "website."
isn't found in title
titlecheck = title.indexOf("website.") > 0 ? "found" : "not found";
alert(titlecheck);
You could also use String.match(...)
title = document.getElementById('title');
titletxt = title.innerText ? title.innerText : title.textContent
titlecheck = titletxt.match("website.");
if (titlecheck != null ) {
return false;
}
String.match returns null if no match is found, and returns the search string("website.") if a match is found