0

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

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 ).

Sign up to request clarification or add additional context in comments.

2 Comments

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

Javascript functions are case sensitive - indexOf not IndexOf

Comments

1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.