I think I may have an interesting solution. Please take a look at the following snippet and let me know if it works for you.
You can read about Regular Expressions on MDN.
Then about the RegExp Constructor. Here is the key. Not everyone know that you can generate Regular Expressions dynamically.
Update:
The idea is to traduce the 'wildcard' syntax into a RegExp syntax, like this:
?
means: 'any single number', in RegExp: [0-9]
or d
*
means: 'one or more numbers', in RegExp: .+
(actually this means one or more 'anything')
This is why I do the double replacement at the beginning before feeding the query to the RegExp constructor.
Finally, yes, this can be extended to work with non number characters. It is sufficient to replace [0-9]
with .
function queryNumbers(array, query) {
const src = query.replace(/?/g, '[0-9]').replace(/*/g, '.+');
const regexp = new RegExp('^' + src + '$');
return array.filter((item) => regexp.test(item));
}
const mobileNumbersArray = ['830456481', '831456481', '9886503103'];
console.log(queryNumbers(mobileNumbersArray, '*'));
console.log(queryNumbers(mobileNumbersArray, '83*'));
console.log(queryNumbers(mobileNumbersArray, '*456*'));
console.log(queryNumbers(mobileNumbersArray, '9886503103'));
console.log(queryNumbers(mobileNumbersArray, '83?4*'));
console.log(queryNumbers(mobileNumbersArray, '8*'));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…