I want to compare a string and and array in order to get words or phrases in the string that are present in the array; but I do not want to include words from the string that are not surrounded by whitespaces.
The below code compares userInput and myArray and produced this result: morning,good,good morning,go,he.
You would see that "go" and "he" are also included, although they are not separate words in userInput ("go" is from "good" and "he" is from "hello"). I researched on regular expression but couldn’t figure out how to use them. I need help on how to exclude "go" and "he" from the result.
const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
const intersect = myArray.filter(word =>
userInput.includes(word)
);
document.write(intersect);
2
Answers
You can instantiate a new
RegExp
for eachphrase
inmyArray
and execute it on theuserInput
.b
)i
) to ignore case sensitivityHere is a an example with with live input evaluation and a debounce:
Regex is very powerful, and I highly recommend you become familiar with it. Using a site like regexr.com will help, because you can test things there instantly.
The
b
part is a word boundary (with two‘s because they need to be escaped)