Tl, др
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
}
Полный ответ:
Чтобы ответить на ваш вопрос, я предложил следующий метод:
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');
}
Это создаст новый RegEx, который помещает дополнительный пробел между каждым символом.
Это означает, что с данной строкой icecream
вы получите RegEx, который выглядит следующим образом:
/i(\s)*c(\s)*e(\s)*c(\s)*r(\s)*e(\s)*a(\s)*m/i
Это регулярное выражение будет соответствовать во всех следующих случаях:
- я cecream
- ic ecream
- мороженое <= Это ваше! </li>
- ледяное поле
- icecr eam
- Ледяной берег
- Мороженое, м
- 1035 * мороженное *
Весь метод также может быть сокращен до этого:
let input = new RegExp(input.split('').join('(\\s)*').concat(`|${input}`), 'i');
Он довольно короткий, но также нечитаемый.
Встроенный в ваш код, он выглядит так:
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...');
}
Или это:
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
}