使用javascript检查字符串中是否包含单词/字母

时间:2017-05-09 06:45:46

标签: javascript

我找不到在子字符串中搜索字母/字符串的方法。目标是在找到字符串时创建警报。感谢

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>

3 个答案:

答案 0 :(得分:2)

DOM元素没有indexOf,但在您的示例中,string是一个DOM元素,因为您正在使用通过提供{创建的自动全局 {1}} div

要获取id="string"的内容,您需要使用其innerHTMLinnerTexttextContent属性。

我也不会提倡使用自动全局变量(尽管它们现在在规范中),因为那里有太多冲突的全局变量。相反,我会明确使用div

getElementById
function validate() {
  if (document.getElementById("string").innerHTML.indexOf('worlds') > -1) {
    alert("word found");
  }
}

答案 1 :(得分:0)

您应该通过调用innerHTMLdocument.getElementById

来获取DOM元素document.querySelector

您也可以直接使用String#includes()

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

<button id="button" onclick="validate()">click me</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以先使用document.getElementById('string').innerHTML

定义string变量

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>

相关问题