When dealing with varying input, it becomes necessary to dynamically generate the regular expression.
In the following function, we are essentially constructing a string and then using new RegExp(string, 'i')
to create the regular expression.
The pattern of the expression begins with a caret, followed by:
^[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*
Note that \w*
is appended after each input string, and \s+
is if it's not the last input string (meaning, not the end).
function generateRegex (input) {
var string = '^', arr = input.trim().split(' ');
arr.forEach(function (chars, i) {
string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
});
return new RegExp(string, 'i');
}
You can then utilize the .filter()
method on your array to retrieve the matching elements:
var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
return value.match(generateRegex('Gur Ha'));
});
Result:
'Gur Ha'
finds a match: ["Gurken halbiert 2kg"]
'Gur'
finds matches:
["Gurken halbiert 2kg", "Gurken RW"]
'Kar g 5'
finds a match: ["Karotten geschnitten 5kg"]
'G r'
finds a match: ["Gurken RW"]
Example:
function generateRegex (input) {
var string = '^', arr = input.trim().split(' ');
arr.forEach(function (chars, i) {
string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
});
return new RegExp(string, 'i');
}
var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
return value.match(generateRegex('Gur'));
});
document.body.textContent = JSON.stringify(filteredArray);