How can I make a partial string match in Javascript?
e.g. to match 'Alf'
- 'Alfred' -> true
- 'Alf' -> true
- 'alf' -> true
- 'al' -> true
- 'altered' -> false
- 'half' -> false
- '' -> false
- 'bob' -> false
https://jsfiddle.net/zbzc5tqe/1/
I would welcome shorter / more use of javascript inbuilt functions.
var arr = ['Alfred', 'Alf', 'alf', 'al', 'altered', 'half', '', 'bob']; arr.forEach(function(element) { add(element + "->" + matches(element, 'Alf')); }); function ignoreCase(s1, s2) { var needleRegExp = new RegExp('^' + s2 + "$", "i"); return needleRegExp.test(s1) } function partializer(string) { var out = []; for (var i = 1; i < string.length; i++) { out.push(string.slice(0, i)); } return out; } function matches(text, partial) { var parts = partializer(partial); for (var i = 0; i < parts.length; i++) { if (startsWith(text, parts[i])) { return true; } } return false; } function startsWith(text, element) { var s2 = text.split(0, element.length - 1); return ignoreCase(element, s2); } function add(text) { var olList = document.getElementById('list'); var newListItem = document.createElement('li'); newListItem.innerText = text; olList.appendChild(newListItem); } <ol id="list"> </ol>