请看下面的代码
<!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");
//Convert the entire word list to upper case
for(var i=0;i<listOfWordsArray.length;i++)
{
listOfWordsArray[i] = listOfWordsArray[i].toUpperCase();
}
//Get the paragrah text
paragraph = document.getElementById("paragraph").value;
paragraphArray = paragraph.split(" ");
//Convert the entire paragraph to upper case
for(var i=0; i<paragraphArray.length; i++)
{
paragraphArray[i] = paragraphArray[i].toUpperCase();
}
//check whether paragraph contains words in list
for(var i=0; i<listOfWordsArray.length; i++)
{
/* if(paragraph.contains(listOfWords[i]))
{
wordCounter++;
}*/
re = new RegExp("\\b"+listOfWordsArray[i]+"\\b");
if(paragraph.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
其中包含多少个单词wordList
。中的单词wordList
用换行符分隔。
但是,我需要此检查不区分大小写。例如,“count”、“COUNT”和“Count”之间应该没有区别。
但是在这里,我总是得到答案 0。我在这里做错了什么?
更新
我尝试了 SO User 'Kolink' 提供的以下功能。然而,它在不同的运行中给出了不同的答案。在最初的几次运行中它是正确的,然后它开始提供错误的答案!也许 JavaScript 作为static
变量?