3 examples of 'count words javascript' in JavaScript

Every line of 'count words javascript' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
1function countWords(input) {
2 let words = [];
3 for (let i = 0; i < input.length; i++) {
4 words = words.concat(input[i]
5 .toLowerCase()
6 .split(/\W+/)
7 .filter(x => x !== ''));
8 }
9
10 let map = new Map();
11 for (let i = 0; i < words.length; i++) {
12 let currentWord = words[i];
13 if(!map.has(currentWord)){
14 map.set(currentWord, 1);
15 continue;
16 }
17
18 map.set(currentWord,map.get(currentWord) + 1);
19 }
20
21 let arr = Array.from(map).sort();
22 for (let key of arr) {
23 console.log(`'${key[0]}' -> ${key[1]} times`)
24 }
25}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

6function countEachWord( textInput ) {
7 // split up input string into arrays by spaces and newline chars
8 const whiteSpaceChars = /\s/;
9 const allWords = textInput.split(whiteSpaceChars);
10
11 let wordCountObject = {};
12
13 for (var i = 0; i < allWords.length; i++) {
14 // get rid of punctuation and make word lowercase
15 let currentWord = allWords[i].replace(/\W/g, '').toLowerCase();
16 if (!wordCountObject[currentWord]) {
17 wordCountObject[currentWord] = 1;
18 } else {
19 wordCountObject[currentWord] += 1;
20 }
21 }
22
23 return wordCountObject;
24}
9export function wordCount (string) {
10 return string ? (string.replace(/['";:,.?¿\-!¡]+/g, '').match(/\S+/g) || []).length : 0
11}

Related snippets