匹配2个字符串

时间:2013-09-07 16:45:52

标签: 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;
    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个单词并计数,并且不应因为悔改而忽略它。

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

3 个答案:

答案 0 :(得分:3)

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

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

您不需要引号

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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

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

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

而不是

if(listOfWordsArray.match(re))
{
    wordCounter++;
}