RegExp
When selecting text items it is always best to use regular expressions. They take a little time to master but there are plenty of online resources, editors, and testers that help.
RegExps are available in many computer languages, but as with all standards there are many differences so be sure to use the correct language (ECMAScript / JavaScript) version.
Words beginning with *
For your select (AKA filter) you want to match any string that contains a word starting with "ma"
or whatever. The regular expression would be /\bma/i
- the
/
starts a expression. - the
\b
means word boundary - the
ma
the two characters to match - the
/
closes the expression - the
i
is a search flag meaning case insensitive
You will need to build the expression as needed so use the constructor to create the expression
// Note that the "\\" escape backslash creates a single "\" const exp = new RegExp("\\b" + searchString, "i");
Putting it into a function, you use exp.test(str)
which returns true
or false
depending on the str
. Note that you can not just use exp.test
as a callback for filter
, names.filter(exp.test)
will throw an error. You need to either bind the function to the expression or supply the context
Thus the more elegant solution is
function filterNamesStartingWith(startStr, names) { const exp = new RegExp("\\b" + startStr, "i"); return names.filter(name => exp.test(name)); } // or maybe you prefer function filterNamesStartingWith(startStr, names) { const exp = new RegExp("\\b" + startStr, "i"); return names.filter(exp.test, exp); }