Roland Warburton
Roland Warburton

Reputation: 73

check if a word/letter is contained in a string with javascript

I cant find a way to search for a letter/string within a substring. the objective is to create an alert if the string is found. Thanks

https://jsfiddle.net/1rawcotx/2/

function validate() {
  if (string.indexOf('worlds') > -1) {
    alert("word found");
  }
}
<div id="string">
  worlds and some other text
</div>

<button id="button" onclick="validate()">click me</button>

Upvotes: 0

Views: 362

Answers (3)

prasanth
prasanth

Reputation: 22500

You could define string variable first, using document.getElementById('string').innerHTML

function validate() {
var string =document.getElementById('string').innerHTML;
  if (string.indexOf('worlds') > -1) {
    alert("word found");
  }
}
<div id="string">
  worlds and some other text
</div>

<button id="button" onclick="validate()">click me</button>

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074295

DOM elements don't have an indexOf, but in your example, string is a DOM element because you're using the automatic global created by giving your div id="string".

To get the contents of the div, you'd use its innerHTML or innerText or textContent properties.

I also wouldn't advocate using automatic globals (although they're in the spec now), because there are too many conflicting globals out there. Instead, I would explicitly use getElementById:

function validate() {
  if (document.getElementById("string").innerHTML.indexOf('worlds') > -1) {
    alert("word found");
  }
}
<div id="string">
  worlds and some other text
</div>

<button id="button" onclick="validate()">click me</button>

Upvotes: 2

Weedoze
Weedoze

Reputation: 13943

You should get the DOM element innerHTML by calling document.getElementById or document.querySelector

You can also directly use String#includes()

const divValue = document.querySelector('#string').innerHTML;
function validate() {
  if (divValue.includes('worlds')) {
    alert("word found");
  }
}
<div id="string">
  worlds and some other text
</div>

<button id="button" onclick="validate()">click me</button>

Upvotes: 0

Related Questions