如何检查给定的单词是否包含在String中?

时间:2013-09-04 09:12:31

标签: javascript html web

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script>
function count()
{
    var listOfWords, paragraph, listOfWordsArray, paragraphArray;
    var wordCounter=0;

    listOfWords = document.getElementById("wordsList").value;

    //Split the words
    listOfWordsArray = listOfWords.split("\n");

    //Get the paragrah text
    paragraph = document.getElementById("paragraph").value;
    paragraphArray = paragraph.split(" ");

    //check whether paragraph contains words in list
    for(var i=0; i<listOfWordsArray.length; i++)
    {
        if(paragraph.contains(wordListArray[i]))
        {
                wordCounter++;
        }
    }

    window.alert("Number of Contains: "+wordCounter);
}
</script>

</head>


<body>
<center>
<p> Enter your Word List here </p>
<br />
<textarea id="wordsList" cols="100" rows="10"></textarea>

<br />
<p>Enter your paragraph here</p>
<textarea id="paragraph" cols="100" rows="15"></textarea>

<br />
<br />
<button id="btn1"  onclick="count()">Calculate Percentage</button>

</center>
</body>
</html>

在这里,我要做的是计算paragraph中包含在wordList中的任意数量的单词数量。wordList paragraph中的单词用新行分隔。

但是,我在这里没有得到任何输出。我不是很喜欢网络和脚本语言,所以我没能找到背后的东西。

如何计算wordList中包含的{{1}}中有多少字?请解释为什么它没有显示出来?

3 个答案:

答案 0 :(得分:1)

如果您只想要发生,请使用indexOf字符串方法。使用RegExp仅检查整个字词。像这样改变条件(统计整个单词):

//check whether paragraph contains words in list
for (var i = 0; i < listOfWordsArray.length; i++) {
    re = new RegExp("\\b" + listOfWordsArray[i] + "\\b");
    if (paragraph.match(re)) {
        wordCounter++;
    }
}

点击此处:http://jsfiddle.net/EuhEE/

答案 1 :(得分:1)

你刚买错了

//check whether paragraph contains words in list
for(var i=0; i<listOfWordsArray.length; i++)
{
    if(paragraph.contains(wordListArray[i]))
    {

请参阅wordListArray不存在,应为listOfWordsArray

http://jsfiddle.net/PW7jZ/

答案 2 :(得分:1)

如果您知道textarea只会包含文本,请使用此

var count = document.getElementById('content').innerHTML.split(' ').length;

如果textarea中可以包含HTML标记,那么您将不得不遍历其子项以查找文本节点:

function get_text(el) {
    ret = "";
    var length = el.childNodes.length;
    for(var i = 0; i < length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType != 8) {
            ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
        }
    }
    return ret;
}
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;

这与jQuery库用于实现其text()函数效果的逻辑相同。 jQuery是一个非常棒的库,在这种情况下是没有必要的。但是,如果您发现自己正在进行大量的DOM操作或AJAX,那么您可能需要查看它。