You can use the String.prototype.replace()
function. It won't be one line of code, but it'll be pretty simple:
var regex = /((word1?)|(word2?)|(word3?)|(word4?)|(word5 ?)|(word6?)|(word7?))/gmi;
var counts = {};
var sourceText = yourSourceTextWithWordsInIt;
sourceText.replace(regex, function(_, matched) {
matched = matched.toLowerCase();
counts[matched] = (counts[matched] || 1) + 1;
});
Then the counts
object will contain exactly what you described. The .replace()
function on the String prototype can take a function as its second parameter. Such a function will be called repeatedly when the pattern has the "g" flag. Each call to the function will include as the first parameter the entire matched substring, and the subsequent parameters will be the parenthesized group matches from the regex.