2

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?

Lyon Jenkins
  • 75
  • 1
  • 5
  • 1
    You 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 Answers3

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"));
Community
  • 1
  • 1
Evans M.
  • 1,791
  • 16
  • 20
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