const values = ['Brussels', 'Cairo', 'Casablanca', 'Cangzhou', 'Caracas',
'Los Angeles', 'Osaka'];
const match = (s) => {
const p = Array.from(s).reduce((a, v, i) => `${a}[^${s.substr(i)}]*?${v}`, '');
const re = RegExp(p);
return values.filter(v => v.match(re));
};
console.log(match('Ca')); // Cairo, Casablanca, Cangzhou, Caracas
console.log(match('Caz')); // Cangzhou
console.log(match('as')); // Casablanca, Caracas
console.log(match('aa')); // Casablanca, Caracas, Osaka
Run code snippet
var strings = ["Cairo", "Casablanca", "Cangzhou", "Carcas"]; // Your array of things to filter
function disp(matches) {
// Displays the filtered results on the page
var results = document.getElementById("suggestions");
results.innerHTML = matches.join("<br>");
}
function regExpTest(inputString, regex) {
// Checks to see if what the user typed matches any items in gucciArray
return regex.test(inputString);
}
function typeKey(event) { // This function is supposed to be called whenever the user types a letter in the text box
var textTyped = event.target.value; // What the user typed in the text box;
var filter = new RegExp(textTyped.split('').join('.*'), 'i'); // Matches anything with the characters that the user typed, in order, with any characters inbetween them
// Filter the array
// Returns a new array containing the items from the old array that pass the RegExp test
var filteredArray = strings.filter(s => regExpTest(s, filter));
// Display the filtered results on the page
disp(filteredArray);
}
disp(strings);
const values = ['Brussels', 'Cairo', 'Casablanca', 'Cangzhou', 'Caracas',
'Los Angeles', 'Osaka'];
const match = (s) => {
const p = Array.from(s).reduce((a, v, i) => `${a}[^${s.substr(i)}]*?${v}`, '');
const re = RegExp(p);
return values.filter(v => v.match(re));
};
console.log(match('Ca')); // Cairo, Casablanca, Cangzhou, Caracas
console.log(match('Caz')); // Cangzhou
console.log(match('as')); // Casablanca, Caracas
console.log(match('aa')); // Casablanca, Caracas, Osaka
Run code snippet