EN
JavaScript - search array for substring match
0 points
In this article, we would like to show you how to search an array for substring match in JavaScript.
In this example, we use filter()
and includes()
methods to search for elements inside the array
that contain 'id'
substring.
xxxxxxxxxx
1
const array = ['a', 'b', 'id-1-value1', 'c', 'id-2-value2'];
2
3
const results = array.filter((element) => element.includes('id'));
4
5
console.log(results); // [ 'id-1-value1', 'id-2-value2' ]
In this section, as the argument of filter()
we use RegExp test()
method to match the elements that start with given pattern - in this case id
.
xxxxxxxxxx
1
const array = ['a', 'b', 'id-1-value1', 'c', 'id-2-value2'];
2
const pattern = /^id/;
3
4
const results = array.filter((element) => pattern.test(element)); // tests for "id-" in the beginning of the element
5
6
console.log(results); // [ 'id-1-value1', 'id-2-value2' ]
Note:
^
in regular expressions matches the beginning of a string.