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.
1. Using filter() with includes() method
In this example, we use filter() and includes() methods to search for elements inside the array that contain 'id' substring.
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'id-1-value1', 'c', 'id-2-value2'];
const results = array.filter((element) => element.includes('id'));
console.log(results); // [ 'id-1-value1', 'id-2-value2' ]
2. Using filter() with test() method
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.
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'id-1-value1', 'c', 'id-2-value2'];
const pattern = /^id/;
const results = array.filter((element) => pattern.test(element)); // tests for "id-" in the beginning of the element
console.log(results); // [ 'id-1-value1', 'id-2-value2' ]
Note:
^in regular expressions matches the beginning of a string.