0

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']
Nadhas
  • 5,421
  • 2
  • 28
  • 42
  • Use the available [`String`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods) and [`RegExp`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#instance_methods) methods. Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). It’s strange seeing two upvotes on a question without any attempt. – Sebastian Simon Sep 09 '21 at 05:43

2 Answers2

7

You can use array's filter using following regex

/\dxyz/

enter image description here

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/

enter image description here

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • console.log('Banana2345xyz'.match(/\dxyz/)) is identifying only one number "5xyz". How to get all digits 2345 (without xyz suffix) ? – Nadhas Sep 09 '21 at 10:18
  • @Udhaya Then you can use `console.log("Banana2345xyz".match(/\d+/));` – DecPK Sep 09 '21 at 14:37
1

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)));
smac89
  • 39,374
  • 15
  • 132
  • 179