0

请看下面的代码

<!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;
    listOfWords = listOfWords.toUpperCase();

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



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


    //check whether paragraph contains words in list
    for(var i=0; i<paragraphArray.length; i++)
    {

        re = new RegExp("\\b"+paragraphArray[i]+"\\b","i");

        if(listOfWordsArray.match(re))
        {
            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并检查段落中有多少单词在listOfWords. 这不应该省略单词重复,这意味着如果段落中有2​​个或多个相同的单词(例如:2个“农民”单词),则应将其视为2个单词并计数,不应因悔改而省略。

现在,我的代码没有提供任何输出,我不知道为什么。

4

3 回答 3

3

您正在寻找要拆分的字符串,而不是正则表达式

listOfWordsArray = listOfWords.split("/\r?\n/");

你不想要引号

listOfWordsArray = listOfWords.split(/\r?\n/);
于 2013-09-07T16:49:26.460 回答
1

除了已经指出的代码的所有问题,我个人会完全避免使用正则表达式,只需检查索引:

function count() {
  var listOfWords, paragraph, listOfWordsArray, paragraphArray, wordCounter; 
  wordCounter = 0;
  listOfWordsArray = document.getElementById('wordsList').value.toUpperCase().split(' ');
  paragraphArray = document.getElementById('paragraph').value.toUpperCase().split(' ');
  for (var i = 0, l = paragraphArray.length; i < l; i++) {

    if (listOfWordsArray.indexOf(paragraphArray[i]) >= 0) {
      wordCounter++;
    }

  }
  window.alert('Number of Contains: ' + wordCounter);
}
于 2013-09-07T17:06:24.300 回答
0

首先删除正则表达式周围的引号。然后尝试类似

for(var i=0;i<listOfWordsArray.length;i++)
{
    if(listOfWordsArray[i].match(paragraphArray[i])
    {
        wordCounter++;
    }
}

代替

if(listOfWordsArray.match(re))
{
    wordCounter++;
}
于 2013-09-07T17:12:13.423 回答