最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - filter with wildcard (*) - Stack Overflow

programmeradmin1浏览0评论

I want to filter over a collection of items with an eventual wildcard.

Let's say, I have the following items:

const items = ['Banana', 'Apple', 'Melon']

I now want to filter with the following strings:

e

Expected output: None

*e

Expected output: Apple

*e*

Expected output: Apple, Melon

ana

Expected output: None

*ana

Expected output: Banana

*an

Expected output: none

*an*

Expected output: Banana

I hope you get my intention. Is there any smart way to do it with regex or standard JS functions / libraries? I couldn't find something so far.

I want to filter over a collection of items with an eventual wildcard.

Let's say, I have the following items:

const items = ['Banana', 'Apple', 'Melon']

I now want to filter with the following strings:

e

Expected output: None

*e

Expected output: Apple

*e*

Expected output: Apple, Melon

ana

Expected output: None

*ana

Expected output: Banana

*an

Expected output: none

*an*

Expected output: Banana

I hope you get my intention. Is there any smart way to do it with regex or standard JS functions / libraries? I couldn't find something so far.

Share Improve this question asked Sep 3, 2018 at 5:09 nsoethnsoeth 3812 gold badges6 silver badges17 bronze badges 1
  • Reference Link : stackoverflow.com/questions/12695594/… – Nareen Babu Commented Sep 3, 2018 at 5:16
Add a comment  | 

1 Answer 1

Reset to default 17

You can construct a regular expression by replacing *s with .* to match any characters, and surround the wildcard string with ^ and $ (to match the beginning and the end):

const items = ['Banana', 'Apple', 'Melon']

const filterBy = str => items.filter(
  item => new RegExp('^' + str.replace(/\*/g, '.*') + '$').test(item)
);
console.log(filterBy('e'));
console.log(filterBy('*e'));
console.log(filterBy('*e*'));
console.log(filterBy('ana'));
console.log(filterBy('*ana'));
console.log(filterBy('*an'));
console.log(filterBy('*an*'));

Note that if the wildcard string ever has any other characters with a special meaning in a regular expression, you'll have to escape them first.

发布评论

评论列表(0)

  1. 暂无评论