-1

I'm familiar with searching a string for a given substring:

if (string.indexOf(substring) > -1) {
    var containsSubstring = true;
}

But what if the substring needs to be a word?

A word:

  • it must be at the beginning of the string with a space after it; or
  • at the end of the string with a space before it; or
  • in the middle of the string with a space on each side

If I'm looking for the substring fox:

the quick brown fox // matches
fox jumps over the lazy dog // matches
quick brown fox jumps over // matches


the quick brownfox // does not match
foxjumps over the lazy dog // does not match
quick brownfox jumps over // does not match
quick brown foxjumps over // does not match
quick brownfoxjumps over // does not match

Is there any way to achieve the results above with indexOf or will I need to use regex?

Community
  • 1
  • 1

3 Answers3

1

You can use the search method.

var string = "foxs sas"

var search = string.search(/\bfox\b/) >= 0? true : false;

console.log(search)
Rafael Umbelino
  • 654
  • 7
  • 13
1

Have you tried using a regex with word boundaries:

if (/(\bfox\b)/g.test(substring)) {
    var containsSubstring = true;
}

https://regex101.com/r/G3iOGi/1

combatc2
  • 1,085
  • 8
  • 10
0

You can achieve this by checking if it is at the start of the string and has a space after, or is at the end of the string and has a space before, or is in the middle of the string and has a space before and after.

Frank Egan
  • 146
  • 8