javascript - 测试字符串是否包含字符串数组中的单词
问题描述
它不起作用。它总是与其他。我需要使用数组,并查看字符串是否包含数组中的任何单词。请帮忙,这真的很烦人
function buttonClick() {
var name = document.getElementById('myText').value;
var yourstring = name;
var substrings = ['fruit', 'apple'];
var length = substrings.length;
while (length--) {
if (yourstring.indexOf(substrings[length]) != -1) {
var outcome = 1;
} else {
var outcome = 2;
}
}
switch (outcome) {
case 1:
document.getElementById('fruitvalue').innerHTML = name + 'is ...';
break;
case 2:
document.getElementById('fruitvalue').innerHTML = name + 'is not ...';
break;
}
}
<body>
<center>
Last Name:<input type="text" id="myText" value="">
<button
onClick="buttonClick()"
style="font-family:font; color:blue;"
>Submit</button>
<h2 id="fruitvalue"></h2>
</center>
</body>
</head>
解决方案
我建议您取消循环和 ifs,并通过使用array.some和String.prototype.includes显着减少代码。这段代码可以清楚地写成一行:
function hasWord(str, words) {
return words.some(word => str.includes(word));
}
const name = document.getElementById('myText').value;
const substrings = ['fruit', 'apple'];
const element = document.getElementById('fruitvalue');
function buttonClick() {
const matches = hasWord(name, substrings);
const suffix = matches ? 'is ...' : 'is not ...';
element.innerHTML = `${name} ${suffix}`;
}
<body>
<center>
Last Name:
<input type="text" id="myText" value="">
<button
onClick="buttonClick()"
style="font-family:font; color:blue;"
>Submit</button>
<h2 id="fruitvalue"></h2>
</center>
</body>
推荐阅读
- matlab - 如何使用 for 循环提取列?
- appium - 设置Appium后会弹出找不到aapt
- java - 如何在片段内制作导航抽屉?
- excel - 所需对象错误,运行错误 424
- excel - wb.close 上的对象所需的运行时错误 424
- javascript - 如何在悬停时用关键帧动画文本替换文本?
- laravel - 如何在 Laravel 查询中按第二个关系排序?
- android - Retrofit2发布数组以匹配php数组参数
- python - 在 CSV 文件中查找最高均值
- php - 使用 oscarotero/gettext 翻译库时无法重新声明 Laravel 的 __() 函数