Page 1 of 1

javascript help needed

Posted: Tue Jan 10, 2012 2:57 pm
by robbaust
Hi please could someone point me in the right direction

I have to do a piece of javascript that asks the user to type in a sentence then print out each word on a separate line then count out a given letter (say the letter A) and display how many times that letter appears in that word the number also needs to appear beside that word so say apple a day keeps the doctor away would print out

apple 1
a 1
day 1
keeps 0
the 0
doctor 0
away 2

I hope this makes sense

here is my code

cheers rob
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Words with an A</title>
<script type="text/javascript">
        var theText = prompt('Please enter the text that you want to check')
        
        function WordsWithA(phrase)
        {
                this.phrase = phrase                                                                            // Assign paramater phrase to the variable phrase
                var wordsArray = phrase.split(" ");                                                     // Split the phrase into indivisual words
                var aWordCount = 0;                                                                                     // Create variable that will contain the number of words with the letter a in
                
                for(var i=0; i<wordsArray.length; i++)                                          // Loop over the words array
                        {
                                document.write(wordsArray+ "<br />")                         // Output each word to the document and add a line break after each one
                                if(wordsArray.indexOf("a") > -1)                                     // Check to see if the word contains a letter a
                                        {
                                                aWordCount +=1;                                                         // If the word contains a letter a, add one to the count
                                        }
                        }
                
                alert(aWordCount + " of the provided words contain the letter a");      // Output the number of words with an a in an alert dialogue
                
        }       

        WordsWithA(theText);

</script>

</head>
<body>

Re: javascript help needed

Posted: Wed Jan 11, 2012 12:47 am
by jacek
You can remove
this.phrase = phrase 
since you don't actually ever use it.

That looks like it is the problem too, since there is no ; at the end of that line it would be causeing a syntax error.