I need to search for initials (not sure if this is the right name, if it isn’t, someone please alter the question) using Javascript. For example:
Search for "mas" using the subject "Abraham Maslow" would return true, and search for "John" in "Johnathan Smith" would also be true. However, search for "gold" on "Marygold Ding" would be false.
I initially thought of:
function search(initial, subjectsArray) {
var result = [];
var tmp = null;
var initialLowercase = initial.toLowerCase();
for (var i = 0; i < subjectsArray.length; i++) {
tmp = subjectsArray[i].toLowerCase();
if (tmp.startsWith(initialLowercase)
|| tmp.indexOf(' ' + initialLowercase) != -1) {
result.push(subjectsArray[i]);
}
}
return result;
}
How to optimize this code?
Seems like you want to use “word boundary” matching in a case-insensitive regex, for example:
/\bmas/i.test("Abraham Maslow") === true/\bJohn/i.test("Johnathan Smith") === true/\bgold/i.test("Marygold Ding") === false\bwill match the beginning or end of a word, and theiat the end of the regex makes it case insensitive so thatmascan matchMaslow.— update:
If your strings contain accented chars, the \b will match on them even though we consider them to be part of the word. In that case you want to use
(^|\s)instead, to match “start of string or some whitespace”:/(^|\s)c/i.test('Drácule Smith') === false/(^|\s)dr/i.test('Drácule Smith') === true/(^|\s)smi/i.test('Drácule Smith') === trueMDN regex documentation.