Reputation: 23035
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;
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>
I am trying to iterate through the paragraph
and check how many words in paragraph are inside the listOfWords
. This should not omit words repetition , which means if there are 2 or more same words (ex: 2 "farmer" words) in paragraph, it should take it as 2 words and count and should not omit it because of the repentance.
Right now, my code is not providing any output, I don't know why.
Upvotes: 0
Views: 67
Reputation: 63587
All the issues with the code that have been pointed out aside, I'd personally avoid the regex altogether and just run a check on the index:
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);
}
Upvotes: 1
Reputation: 2287
First remove the quotes around the regex. Then try something like
for(var i=0;i<listOfWordsArray.length;i++)
{
if(listOfWordsArray[i].match(paragraphArray[i])
{
wordCounter++;
}
}
instead of
if(listOfWordsArray.match(re))
{
wordCounter++;
}
Upvotes: 0
Reputation: 207557
You are looking for a string to split, not a regular expression
listOfWordsArray = listOfWords.split("/\r?\n/");
You do not want the quotes
listOfWordsArray = listOfWords.split(/\r?\n/);
Upvotes: 3