The task is to convert a string into a type object:
- property name is a word from a string,
- property value is the number of entries in the string.
Wrote function:
function countWords(str) { var arr = str.split(' '); var obj = {}; for (var i = 0; i < arr.length; i++) { var word = arr[i]; obj[word] = str.split(word).length - 1; } return obj; } console.log(countWords('ask a bunch get a bunch')); // Результат --> {ask: 1, a: 3, bunch: 2, get: 1} // Ожидаемый результат --> {ask: 1, a: 2, bunch: 2, get: 1} How to ensure that 'a' from the word 'ask' is not considered the occurrence of the word 'a'?
I tried regular expressions, but I don’t understand how to attach '\ b' to the word variable in split (word).
obj[word]++you just can not do it because ...? - teran