'JS QUESTION: how can i make it so that when im detecting a word inside a string, i check standalone words like Hello

How do i check for the word "Hello" inside a string in an if statement but it should only detect if the word "Hello" is alone and not like "Helloo" or "HHello"



Solution 1:[1]

The easiest way to do such thing is to use regular expressions. By using regular expressions you can define a rule in order to validate a specific pattern. Here is the rule for the pattern you required to be matched:

  • The word must contain the string "hello"
  • The string "hello" must be preceded by white-space, otherwise it must be the found at the beginning of the string to be matched.
  • The string "hello" must be followed by either a '.' or a white-space, Otherwise it must be found at the end of the string to be matched.

Here is a simple js code which implements the above rule:

let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|\s)hello(\s|.|$)/gi;
/*const pattern = /\bhello\b/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);

In the above code I assumed that the pattern is not case sensitive. That is why I added case insensitive modifier ("i") after the pattern. I also added the global modifier ("g") to match all occurrence of the string "hello".

You can change the rule to whatever you want and update the regular expression to confirm to the new rule. For example you can allow for the string to be followed by "!". You can do that by simply adding "|!" after "$".

If you are new to regular expressions I suggest you to visit W3Schools reference: https://www.w3schools.com/jsref/jsref_obj_regexp.asp

Solution 2:[2]

One way to achieve this is by first replacing all the non alphabetic characters from string like hello, how are you @NatiG's answer will fail at this point, because the word hello is present with a leading , but no empty space. once all the special characters are removed you can simply split the string to array of words and filter 'hello' from there.

let text = "hello how are you doing today? Helloo HHello";

// Remove all non alphabetical charachters
text =  text.replace(/[^a-zA-Z0-9 ]/g, '')

// Break the text string to words
const myArray = text.split(" ");

const found = myArray.filter((word) => word.toLowerCase() == 'hello')

// to check the array of found ```hellos```
console.log(found)

//Get the found status
if(found.length > 0) {
    console.log('Found') 
}

Result

['hello']
Found

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Salman Malik