Reputation: 1367
I have a string I want to check if a substring is in the main string. The code I have below works partially. The problem is I want to check if the substring matches per word to the main string currently it checks per character. To Explain this better say my main string is the banana is yellow
and if the substring I am looking for is banana is
I want it to print true but if the substring is ana is
it prints false. How can I achieve this?
const testString = 'the banana is yellow'
const checkString = 'ana is'
//should have printed false
if (testString.includes(checkString)) {
console.log('true')
} else {
console.log('false')
}
Upvotes: 0
Views: 54
Reputation: 370729
Turn the needle into a regular expression surrounded by word boundaries.
const testString = 'the banana is yellow'
const checkString = 'ana is'
const pattern = new RegExp('\\b' + checkString + '\\b');
console.log(pattern.test(testString));
If the needle might contain special characters, escape them before passing to the RegExp constructor.
Upvotes: 4