检查一个字/字母是否包含在一个字符串与JavaScript
我无法找到一种方法来搜索字母/字符串内的子字符串。目标是在找到字符串时创建警报。由于检查一个字/字母是否包含在一个字符串与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>
你应该通过调用document.getElementById
或document.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>
您可以定义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>
DOM元素没有一个indexOf
,但在你的例子,string
是DOM元素因为你使用自动全球给你的div
id="string"
。
要获取div
的内容,请使用其innerHTML
或innerText
或textContent
属性。
我也不会主张使用自动全局变量(虽然它们现在在规范中),因为有太多冲突的全局变量。相反,我会明确地使用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>
'> -1'的意义是什么? –
@RolandWarburton:来自*你的*代码。 :-)'indexOf'返回找到子字符串的索引,如果找不到则返回'-1'。使用'> -1'是检查是否被找到的常用方法,尽管我通常使用'!== -1'。两者都很好。在现代JavaScript引擎上,另一种选择是使用'includes'而不是'indexOf',但是一些仍在使用的过时引擎(如IE8)没有它。 –
* “字符串是未定义的变量” *其实,这是不是在OP的代码;这是一个自动的全球(不寒而栗)。 –