I was wondering what the best approach would be to search a javascript array of strings, and return all strings in that array that begin with a given string.
If anybody has any ideas, or if there is an even easier way of achieving this with JQuery please help me out!
For Example,
var arrayOfStrings = ["apple", "banana", "peach", "orange", "plum"];
var searchString = "p";
So if I search arrayOfStrings with searchString it would return plum and peach
EDIT I updated my answer as comments below pointed out, thanks to cookie monster and Havenard
Try array filter
var re = new RegExp('^' + searchString);
var matches = arrayOfStrings.filter(re.test, re);
UPDATE
If you want it case insensitive:
var re = new RegExp('^' + searchString, 'i');
Please note that if your search string contains special characters you would need to escape them first because of the way strings work. Thanks to Alex Pakka for pointing this out.
var searchString = /^p/;
var result = arrayOfStrings.filter(function(str){
return searchString.test(str)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With