Tl;dr
var input = new RegExp('icecream'.split('').join('(\\s)*').concat('|icecream'), 'i');
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.search(input) != -1) {
//do Something
}
Full answer:
To answer your question I proposed the following method:
function makeRegEx(input) {
// The regex for an optional whitespace.
let glueRegex = '(\\s)*';
// Transform the string into an array of characters.
let splittedString = input.split('');
// Join the characters together, with the optional whitespace inbetween.
let joinedString = splittedString.join(glueRegex)
// Add the actual input as well, in case it is an exact match.
joinedString += '|' + input;
// Make a new regex made out of the joined string.
// The 'i' indicates that the regex is case insensitive.
return new RegExp(joinedString, 'i');
}
This will create a new RegEx that places an optional space between each character.
That means that with a given string icecream, you end up with a RegEx that looks like this:
/i(\s)*c(\s)*e(\s)*c(\s)*r(\s)*e(\s)*a(\s)*m/i
This regex will match on all the following cases:
- i cecream
- ic ecream
- ice cream <= This is yours!
- icec ream
- icecr eam
- icecre am
- icecrea m
- icecream
The whole method can also be shortened to this:
let input = new RegExp(input.split('').join('(\\s)*').concat(`|${input}`), 'i');
It is pretty short, but also pretty unreadable.
Integrated into your code it looks like this:
function makeRegEx(input) {
// The regex for an optional whitespace.
let glueRegex = '(\\s)*';
// Transform the string into an array of characters.
let splittedString = input.split('');
// Join the characters together, with the optional whitespace inbetween.
let joinedString = splittedString.join(glueRegex)
// Add the actual input as well, in case it is an exact match.
joinedString += '|' + input;
// Make a new regex made out of the joined string.
// The 'i' indicates that the regex is case insensitive.
return new RegExp(joinedString, 'i');
}
let userInput = 'icecream';
let keywords = "ice cream, ice cream cone, plastic container lid";
let input = makeRegEx('icecream');
// Check if any of the keywords match our search.
if (keywords.search(input) > -1) {
console.log('We found the search in the given keywords on index', keywords.search(input));
} else {
console.log('We did not find that search in the given keywords...');
}
Or this:
var input = new RegExp('icecream'.split('').join('(\\s)*').concat('|icecream'), 'i');
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.search(input) != -1) {
//do Something
}