JSFiddle - React, Tailwind, and code Playground
JavaScript
var splitByDictionary = function (input, dictionary) {
"use strict";
// make sure we're going to look for longest-possible matches first
dictionary.sort(function (a, b) {
return b.length - a.length;
});
var foundWords = [],
remaining = input;
var result = (function match() {
if (remaining.length === 0) {
return true;
}
for (var i = 0; i < dictionary.length; i++) {
if (remaining.substr(0, dictionary[i].length) === dictionary[i]) {
foundWords.push(dictionary[i]);
remaining = remaining.substr(dictionary[i].length);
return match();
}
}
return false;
})();
return result ? foundWords : null;
};
console.log(splitByDictionary("thisisinsane", ["insane", "i", "is", "sin", "in", "this", "totally"]));