-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountWords.js
More file actions
30 lines (22 loc) · 899 Bytes
/
CountWords.js
File metadata and controls
30 lines (22 loc) · 899 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*Task:
Can you implement a function that will return number of words in a string?
You have to ensure that spaces in string is a whitespace for real.
Let's take a look on some examples:
countWords("Hello"); // returns 1 as int
countWords("Hello, World!") // returns 2
countWords("No results for search term `s`") // returns 6
countWords(" Hello") // returns 1
// ... and so on
What kind of tests we made for your code:
Function have to count words and not spaces. You have to be sure that you doing it right
Empty string has no words.
String with spaces around should be trimmed.
Non-whitespace (ex. breakspace, unicode chars) should be treated as a delimiter
Doublecheck that words with chars like -, ', ` are counted right.
*/
//Answer
function countWords(str) {
return str.split(/\s+/).filter(Boolean).length;
}
console.log(countWords("hello"));
console.log(countWords("hello world"));