0

I want to search inside the variable, but I don't want it to search for letters as an

example :

const myText = "Hi Here We go";
console.log(myText.includes("Here")) // true
console.log(myText.includes("ere")) // false
console.log(myText.includes("Here We")) // true
console.log(myText.includes("go")) // true
console.log(myText.includes("i")) // false

1 Answers1

0

One option is to turn the string to search for into a regular expression, and add word boundaries to the left and right side.

const myText = "Hi Here We go";
console.log(/\bHere\b/.test(myText));
console.log(/\bere\b/.test(myText));

If you have to do it dynamically...

const myText = "Hi Here We go";
const validate = needle => (new RegExp('\\b' + needle + '\\b')).test(myText);
console.log(validate('Here'));
console.log(validate('ere'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It really worked!! But /\bHere\b/ what are you doing – user16733810 Jan 30 '22 at 06:54
  • As the answer says, I added word boundaries to the left and right side in a regular expression. – CertainPerformance Jan 30 '22 at 06:54
  • Not working with Arabic letters? – user16733810 Jan 30 '22 at 07:24
  • Arabic letters aren't word characters, so a boundary between an Arabic letter and a non-Arabic-letter won't be reliably matched by `\b`. For that you'll either need an approach like [this](https://stackoverflow.com/q/29729391/9515207) or [this](https://stackoverflow.com/questions/12847333/include-arabic-characters-in-javascript-regular-expression/12847474) combined with lookarounds, or use a different approach. like positive lookarounds for spaces, string delimiters, commas, periods, etc. – CertainPerformance Jan 30 '22 at 14:39