Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search Javascript Array, and return all strings in array that start with X

Tags:

javascript

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

like image 439
Bobby W Avatar asked Jan 30 '26 15:01

Bobby W


2 Answers

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.

like image 54
axelduch Avatar answered Feb 02 '26 06:02

axelduch


var searchString = /^p/;
var result = arrayOfStrings.filter(function(str){
    return searchString.test(str)
};
like image 43
Nik Terentyev Avatar answered Feb 02 '26 07:02

Nik Terentyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!