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')
}

1
  • @Dai nope just edited! Commented Jul 19, 2022 at 3:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why escape special characters? check string banana i*s would reply false.
@seriously because you want all the characters of checkString to be matched literally, and not to be interpreted as any special regular expression syntax.
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.