gpt4 book ai didi

javascript - 如何在Javascript中检查字符串中是否存在数组元素?

转载 作者:行者123 更新时间:2023-12-03 09:14:32 26 4
gpt4 key购买 nike

我有一个包含单词的数组。我还有一根绳子。我需要检查字符串中是否存在数组元素。我尝试过但没有成功。它不起作用。

function inputValidate() {
var val = document.getElementById("title");
var keyWords = ["kerak", "nega", "qanday", "qanaqa", "nimaga", "mi"];
val.value.trim();
len = val.value.length - 1;
lastS = val.value.slice(len);

if (lastS != "?") {
document.getElementById("error").innerHTML = "Savol so`roq belgisi bilan tugashi lozim.";
} else {
document.getElementById("error").innerHTML = " ";
document.getElementById("error").style.color = "red";
}

for (i = 0; i < keyWords.length; i++) {
if (val.indexOf(keyWords[i]) != -1) {
document.getElementById("error2").innerHTML = "Gapingizga so`roq gapga o`xshamadi ";
} else {
document.getElementById("error2").innerHTML = " ";
}
}
}

http://codepen.io/anon/pen/vOMWyQ

最佳答案

I need to check whether an element of array exists in a string.

// The elements you want to be checked in a certain string.
var KEYWORDS = [ 'world' ];

/**
* Checks if an element of a keyword array occurs in a certain text string.
*
* @param {Array} keywords - contains keyword strings
* @param {String} textString - text string to be checked
*
* @return {Boolean} denotes if a match was found.
*/
var keywordExistsInString = function (keywords, textString) {
// Split the text string for easy matching.
var words = textString.slice(/\s*\b\s*/);

// Only interested if ONE of the keywords matches.
// NOTE: if all keywords must match use 'every()' instead of 'some()'.
return keywords.some(function (keyword) {

// Use 'bitwise not' to determine a match.
// Double negate to convert to a Boolean.
return !!~words.indexOf(keyword);
});
};

keywordExistsInString(KEYWORDS, 'hello world'); // true
keywordExistsInString(KEYWORDS, 'hello'); // false

关于javascript - 如何在Javascript中检查字符串中是否存在数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com