Please have a look at the following code
<!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>
Here, what I am trying to do is counting how any number of words are in paragraph
which are also included in wordList
. words in wordList
are separated by new line.
However I need this check to be case insensitive. for an example, there should be no difference between 'count' , 'COUNT' and 'Count'.
But here, I am always getting the answer 0. What am I doing wrong here?
Update
I tried the following function, provided by SO User 'Kolink'. However it is giving different answers in different runs. In first few runs it was correct, then it starts to provide wrong answers! Maybe JavaScript as static
variables?