I'm currently using the string.includes() method to check for the keyword 'rally' in a string. But if I have the text 'Can I have a rally?', it will respond the same as 'Am I morally wrong?'. Is there a way to do this?
            Asked
            
        
        
            Active
            
        
            Viewed 54 times
        
    2
            
            
        - 
                    1You can use a regular expression or some other method to determine that the characters before and after the word 'rally' are either a space, punctuation, the beginning of the string, or the end of the string. That makes sure that the word rally stands on its own and is not a substring of some other word. – Shilly Jan 18 '18 at 12:56
 
3 Answers
1
            
            
        try this
 'Can I have a rally?'.match(/(\w+)/g).indexOf("rally") !== -1  // will return true
 'Am I morally wrong?'.match(/(\w+)/g).indexOf("rally") !== -1 // will return false
        Aswin Ramesh
        
- 1,654
 - 1
 - 13
 - 13
 
0
            
            
        edit Using regular expressions
let text = "Am I mo rally wrong";
function searchText(searchOnString, searchText) {
  searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
}
console.log(searchText(text, "rally"));
- 
                    This will work badly if the `rally` is the first or last word in the sentence. – Greg Jan 18 '18 at 13:04
 - 
                    
 
0
            
            
        maybe you just add space. So morally gives false result. This checks the words possible each position into sentence also whole string is "rally".
var string = "Can I have rally";
console.log(string==="rally" ? true : false || string.includes(' rally') || string.includes('rally ') || string.includes(' rally '));
        krezus
        
- 1,281
 - 1
 - 13
 - 29
 
- 
                    
 - 
                    
 - 
                    1Yeah, this would work. Still https://stackoverflow.com/a/48321982/299774 is much cleaner. – Greg Jan 18 '18 at 17:03