var text = prompt('Please input a text'); var array = text.replace(/\r\n|\r|\n/, ' ').split(' ').sort(); var count = []; for (var i in array) { if (count[array[i]] == undefined) count[array[i]] = 0; count[array[i]]++; } for (var i in count) { console.log(i + ' ' + count[i]); }