I have an array which contains words. Also i have a string. I need to check whether an element of array exists in a string. I've tried but without success. It's not working.
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 = " ";
}
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.