繁体   English   中英

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

[英]check if a word/letter is contained in a string with 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> 

DOM元素没有indexOf ,但是在您的示例中, string是一个DOM元素,因为您使用的是通过给div id="string"创建的自动全局 div

要获取div的内容,可以使用其innerHTMLinnerTexttextContent属性。

我也不会提倡使用自动全局变量(尽管它们现在在规范中),因为那里有太多相互冲突的全局变量。 相反,我将显式使用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> 

您应该通过调用document.getElementByIddocument.querySelector获得DOM元素innerHTML

您也可以直接使用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> 

您可以先使用document.getElementById('string').innerHTML定义string变量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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM