Having a array of string, I want to filter(identify) the strings contain a number followed by 'xyz'.
Input: ['Carrot 22xyz', 'Mango', 'Banana 8xyz each', 'Kiwi']
Output: ['Carrot 22xyz', 'Banana 8xyz each']
Having a array of string, I want to filter(identify) the strings contain a number followed by 'xyz'.
Input: ['Carrot 22xyz', 'Mango', 'Banana 8xyz each', 'Kiwi']
Output: ['Carrot 22xyz', 'Banana 8xyz each']
You can use array's filter using following regex
/\dxyz/
const arr = ["Carrot 22xyz", "Mango", "Banana 8xyz each", "Kiwi"];
const result = arr.filter((s) => s.match(/\dxyz/));
console.log(result);
Note: This will also filter out the result if a number
followed by xyz
that is a part of a string like "apple4xyz", "mango69xyzfast",
If you only want to filter out that is not part of a substring then you can do as:
/\b\d+xyz\b/
const arr = [
"Carrot 22xyz",
"Mango",
"Banana 8xyz each",
"Kiwi",
"apple4xyz",
"mango69xyzfast",
];
const result = arr.filter((s) => s.match(/\b\d+xyz\b/));
console.log(result);
The regex you need is /\dxyz/
. Here is how you use it
const input = ['Carrot 22xyz', 'Mango', 'Banana 8xyz each', 'Kiwi']
console.log(input.filter(mabFruit => /\dxyz/.test(mabFruit)));