How to count the words in a String in JavaScript-Code Examples

Radu TM

How to count the words in a String in JavaScript

JavaScript by Radu TM June 22, 2022

const str = "How to count the words in a String in JavaScript";

// Use a regular expression to remove punctuation and convert to lowercase
const cleanStr = str.replace(/[^\w]/g, "").toLowerCase();

// Split the string into an array of words
const wordArray = cleanStr.split(" ");

// Use a Set to get unique words
const uniqueWords = new Set(wordArray);

// Get the length of the Set (unique words)
const wordCount = uniqueWords.size;

console.log(`There are ${wordCount} unique words in the string.`);

0

21.246

How to count the words in a String in JavaScript

JavaScript by Radu TM June 22, 2022

// initialize a variable to hold the count
let wordCount = 0;

// create a function to count the words in a string
const countWords = str => {
  // create an array of words by splitting the string at spaces
  const words = str.split(' ');

  // set the wordCount variable to the length of the words array
  wordCount = words.length;
};

// call the function and pass in a string
countWords('I ❤️ JavaScript!');

// log the wordCount variable to the console
console.log(wordCount); // 3

0

21.246

How to count the words in a String in JavaScript

JavaScript by Radu TM June 22, 2022

const string = "I ❤️ JS";

// we can use string.split to create an array of words
// then, we use the .length property to count the number of items in the array
const count = string.split(" ").length;

console.log(count); // 3

0

21.246

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories