This function returns the number of characters in a string of text:
const charCount = text => [...text.normalize()].length const wordCount = text => text.trim() ? text.trim().split(/\s+/).length : 0 let s = "Banana 🍩🥕 Apple" console.log(charCount(s)) // Correct: 15 console.log(s.length) // Wrong: 11 console.log(wordCount(s)) // Correct: 3
In most circumstances it would be enough to use text.length to calculate the number of characters in a string, but some unicode characters such as emojis can be counted as more than one. To get round this, we can use the normalize method as well as the spread operator to turn the string into an array and count the elements of the array instead (see linked article below for more info).
To count the number of words in a string, we first use the trim() method to remove any whitespace at the start and end of the string. If this results in an empty string, then it will evaluate to false, so we use the conditional ternary operator to return 0. Otherwise, we use a regular expression that splits the string up based on any whitespace characters (such as spaces, tabs and carriage returns). Each ‘word’ is then placed in an array and we can count the number of elements in that array.