count number of words
in a string
[ for loop | trim | split | length ]

Count number of words in a string

Write a function that takes a string and returns the number of words found in that string.


Example ...

Enter a string ...

"The quick brown fox jumps over the lazy dog" string

9 number of words found in string.

"Kill two birds with one stone" string

6 number of words found in string.

Strings are a sequence of zero or more characters written inside quotes used to represent text.

Strings may consist of letters, numbers, symbols, words, or sentences.

Strings are immutable, they cannot be changed.

Each character in a string has an index.

The first character will be index 0 the second character will be index 1 and so on.

There are two ways to access an individual character in a string.

charAt() method

const str1 = "abc"; string

str1.charAt(0); character at index 0 → "a"

str1.charAt(1); character at index 1 → "b"

str1.charAt(2); character at index 2 → "c"

str1.charAt(3); character at index 3 → "" index not found

Alternatively use at() or slice() methods

bracket notation []

const str2 = "abc"; string

str2[0]; character at index 0 → "a"

str2[1]; character at index 1 → "b"

str2[2]; character at index 2 → "c"

str2[3]; character at index 3 → undefined index not found


Arrays are used to store multiple values in a single variable.

Each value is called an element, and each element has a numeric position in the array, known as its index.

Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Arrays can contain any data type, including numbers, strings, and objects.

const arr1 = [2, 4, 6]; array

arr1[0]; element at index 0 → 2

arr1[1]; element at index 1 → 4

arr1[2]; element at index 2 → 6

arr1[3]; element at index 3 → undefined index not found


Numbers are used to represent both integer and floating-point values.

Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴

let num1 = 5; → number

let num2 = 2.5; → number

let num3 = num1 + num2;

console.log(num3); returns ↴

7.5 → number


Count number of words in a string using ↴

for loop → executes a block of code a number of times.

trim() method → removes whitespace from both ends of the string and returns a new string, without modifying the original string.

split() method → splits a string into an array of substrings.

length property → set or return the number of elements in an array.

ternary operator → frequently used as an alternative to an if...else statement.


for loop repeatedly executes a block of code until a specified condition evaluates to false.

The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.

for (let x = 0; x < 4; x++) {

console.log(x);

}

Loop variable x is initialized to 0

Condition x < 4 is checked before each iteration.

The loop will continue to run as long as x is less than 4

The loop repeatedly executes a block of code 4 times, from 0 to 3

For each iteration of the loop, the current value of x is printed to the console.

After each iteration, x is incremented by 1 x++

When x reaches 4 the condition evaluates to false, terminating the loop.

0

1

2

3 → printed to console


trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.

const str3 = " Hello World "; → string with leading and trailing whitespace

str3.trim(); returns ↴

"Hello World" → string without leading or trailing whitespace


split() method splits a string into an array of substrings based on a specified separator (delimiter). The original string is unchanged.

("") separator → string is split between each character.

(" ") separator → string is split at each space character, resulting in an array of words.

const str4 = "Hello"; → string

str4.split(""); returns ↴

["H", "e", "l", "l", "o"] → array

const str5 = "Hello World"; → string

str5.split(" "); returns ↴

["Hello", "World"] → array


length property returns the number of elements in an array.

const arr2 = [1, 2, 3, 4, 5, 6];

arr2.length; returns ↴

6 → there are 6 elements in the array


Ternary Operator

Ternary Operator is frequently used as an alternative to if...else statements.

if (condition) {

expressionIfTrue;

} else {

expressionIfFalse;

}

Ternary Operator takes three operands ↴

condition evaluates to true or false.

? question mark → expression to execute if the condition is truthy

: colon → expression to execute if the condition is falsy

condition ? expressionIfTrue : expressionIfFalse

let score = 75;

let result = score >= 55

? "You passed"

: "You failed";

console.log(result); returns ↴

You passed → first expression executed


Initialize a variable to hold the string to count number of words.

const string1 = "The quick brown fox jumps over the lazy dog"; → user input


Define a function countWords to count number of words in a string.

function countWords(str) {}

The function takes a string as input, str and returns the number of words found in that string.

Initialize word count to zero.

let wordCount = 0 wordCount

Trim whitespace from both ends of the string.

Split the string into an array of characters.

const chars = str.trim().split("") chars

Iterate through each character in the chars array.

for (let x = 0; x < chars.length; x++)

Word boundary check ↴

if (chars[x] === " " && x > 0 && chars[x - 1] !== " ")

Check for spaces that indicate the end of a word,

and check if the current index x is greater than 0 to avoid checking the first character.

chars[x] === " " && x > 0

Check if the previous character is not a space (to avoid counting multiple spaces as additional words).

chars[x - 1] !== " "

If true, a space is found, and the previous character is not a space, the word count is incremented by 1

wordCount++ increment word count

Using a ternary operator, return the total word count, accounting for non-empty strings.

If the string is not empty, it adds one to the count (to account for the last word),

otherwise, it returns zero.

return str.length > 0 ? wordCount + 1: 0


Call the function with ↴

countWords(string1);


Count number of words in a string.

const string1 = "The quick brown fox jumps over the lazy dog";

function countWords(str) {

let wordCount = 0;

const chars = str.trim().split("");

for (let x = 0; x < chars.length; x++) {

if (chars[x] === " " && x > 0 && chars[x - 1] !== " ") {

wordCount++;

}

}

return str.length > 0 ? wordCount + 1 : 0;

}

call function

countWords(string1); returns ↴

9

Count number of words in a string