0

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')
}
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
seriously
  • 1,202
  • 5
  • 23

1 Answers1

4

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Why escape special characters? check string ```banana i*s``` would reply false. – seriously Jul 19 '22 at 03:02
  • @seriously because you want all the characters of `checkString` to be matched literally, and not to be interpreted as any special regular expression syntax. – Wyck Jul 19 '22 at 03:04
  • Escape the special characters if you would want that to be detected a match (and the special characters aren't on the edge of the needle) – CertainPerformance Jul 19 '22 at 03:04