Shyamal Parikh
Shyamal Parikh

Reputation: 3068

Check if sentence contains a phrase

Sentences:

  1. Hey checkout Hello World <- SHOULD BE INCLUDED
  2. hello world is nice! <- SHOULD BE INCLUDED
  3. Hhello World should not work <- SHOULD NOT BE INCLUDED
  4. This too Hhhello World <- SHOULD NOT BE INCLUDED

var phraseToSearch = "Hello World";

Do note: sentence.ToLower().IndexOf(phraseToSearch.ToLower()) would not work as it would include all the above sentences while the result should only include sentences 1 and 2

Upvotes: 0

Views: 2964

Answers (2)

Max
Max

Reputation: 11

You probably want to use a regular expression. Here are the things you want to match

  • Text (with spaces surrounding it)
  • ... Text (with space on one side, and end of text on the other)
  • Text ... (with space on one side, and start of side on the other)
  • Text (just the string, on its own)

One way to do it, without a regular expression, is just to put 4 conditions (one for each bullet point above) and join them up with a &&, but that would lead to messy code.

Another option is to split both strings be spaces, and checking if one array was a subarray of another.

However, my solution uses a regular expression - which is a pattern you can test on a string.

Our pattern should

  • Look for a space/start of string
  • Check for the string
  • Look for a space/end of string

\b, according to this, will match spaces, seperators of words, and ends of strings. These things are called word boundries.

Here is the code:

function doesContain(str, query){ // is query in str
    return new RegExp("\b" + query + "\b", "i").test(str)
}

The i makes the match case insensitive.

Upvotes: 1

synthet1c
synthet1c

Reputation: 6282

You can use regular expression to match a character pattern with a string.

The regular expression is simply looking for Hello World the exact letters you are looking for with \b a word border and using the i case insensitive modifier.

Regex has a method test that will run the regular expression on the given string. It will return a true if the regular expression matched.

const phraseToSearch = /\bhello world\b/i

const str1 = 'Hey checkout Hello World'
const str2 = 'hello world is nice!'
const str3 = 'Hhello World should not work'
const str4 = 'This too Hhhello World'

console.log(
  phraseToSearch.test(str1),
  phraseToSearch.test(str2), 
  phraseToSearch.test(str3), 
  phraseToSearch.test(str4)
)

Upvotes: 4

Related Questions