I am running into an issue, I have a similar array of Strings in JS:
var myArray = ["bedroomone", "bedroomonetwo", "bathroom"];
And I would like to retrieve all the elements in the array that contains the keyword 'bedroom'. How can I achieve such result ?
I tried in different ways without getting the desired result. How should I proceed ?
To filter strings of an Array based on length in JavaScript, call Array. filter() method on this String Array, and pass a function as argument that returns true for the specific condition on string length or false otherwise.
You can't use filter() on a string as it is an Array.
String.prototype.indexOf:
var PATTERN = 'bedroom', filtered = myArray.filter(function (str) { return str.indexOf(PATTERN) === -1; });
Regexp:
var PATTERN = /bedroom/, filtered = myArray.filter(function (str) { return PATTERN.test(str); });
String.prototype.includes (only in moderm browsers):
var PATTERN = 'bedroom', filtered = myArray.filter(function (str) { return str.includes(PATTERN); });
var bedrooms = myArray.filter(name => name.includes('bedroom'))
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