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

时间:2015-08-13 14:58:05

标签: javascript arrays string

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

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

1 个答案:

答案 0 :(得分:1)

  

我需要检查数组元素是否存在于字符串中。

// 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