Reputation: 3068
Sentences:
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
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
\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
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