[英]How to check whether an element of array exists in string in Javascript?
我有一個包含單詞的數組。 我也有一個字符串。 我需要檢查數組中的元素是否存在於字符串中。 我已經嘗試過,但是沒有成功。 沒用
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 = " ";
}
}
}
我需要檢查數組中的元素是否存在於字符串中。
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.