问题描述:

 function countTheWords() {

var word = "";

var num;

num = num + 1;

How do i add a counter to this? I'm trying to count how many words there are in a sentence.

I have a test next week that I am studying for and I am stuck on this.

I know that what I have is wrong, so please guide me on how I can count the number of words in a sentence.

 do {

word = prompt("Enter a sentence one word at a time. Enter exit to finish your sentence.");

word = word + 1;

}while(word != "exit");

document.write("There are: " + word + " words in your sentence");

}

网友答案:

You can use something like that:

function wordCounter(word){
   return word.split(' ').length
}
网友答案:

Have you tried:

function countWords(sentence) {
    //Creates an array of all of the words and gets the array's length
    return sentence.split(" ").length;
}

alert(countWords("A very simple function can save lots of time")); // 9
网友答案:

To test how many words are in a sentence you could do something like:

 function wordCount(str){
   return str.match(/\s/g).length+1;
 }

In real practice you won't use prompt or alert, but this might help too:

 var sen = prompt('Please enter a sentence.');
 alert('There are '+wordCount(sen)+' words in your sentence!');
网友答案:

One way to solve this problem is by using Regular Expressions. For every word entered, check for the word exit in it just by doing:

/exit/.test(word);

This will return a boolean value that you can test.

Here is the updated code:

var wordCount = 0;

do {
  word = prompt("Enter a sentence one word at a time. Enter exit to finish your sentence.");
  wordCount++;
}while(/exit/.test(word) === false); 


document.write("There are: " + wordCount + " words in your sentence");

Read up: Regular Expressions - JavaScript | MDN

You can make use of arrays to count the words:

var sentence = "This is a sentence.";

var wordCount = sentence.split(' ').length;

console.log(wordCount);  // check your browser's Javascript console to see the count
网友答案:

you can split based on word separator for example " " and new lines.

an example:

var str = "sample sentence"; // or var str=prompt("Enter a sentence")
var x = str.split(" ");      // use newline or any separator if reqd
document.write(x.length)
相关阅读:
Top