5

So, you can easily check if a string contains a particular substring using the .includes() method.

I'm interested in finding if a string contains a word.

For example, if I apply a search for "on" for the string, "phones are good", it should return false. And, it should return true for "keep it on the table".

Khadar111
  • 151
  • 2
  • 3
  • 12

8 Answers8

17

You first need to convert it into array using split() and then use includes()

string.split(" ").includes("on")

Just need to pass whitespace " " to split() to get all words

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
5

This is called a regex - regular expression

You can use of 101regex website when you need to work around them (it helps). Words with custom separators aswell.


function checkWord(word, str) {
  const allowedSeparator = '\\\s,;"\'|';

  const regex = new RegExp(
    `(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,

    // Case insensitive
    'i',
  );
  
  return regex.test(str);
}

[
  'phones are good',
  'keep it on the table',
  'on',
  'keep iton the table',
  'keep it on',
  'on the table',
  'the,table,is,on,the,desk',
  'the,table,is,on|the,desk',
  'the,table,is|the,desk',
].forEach((x) => {
  console.log(`Check: ${x} : ${checkWord('on', x)}`);
});

Explaination :

I am creating here multiple capturing groups for each possibily :

(^.*\son$) on is the last word

(^on\s.*) on is the first word

(^on$) on is the only word

(^.*\son\s.*$) on is an in-between word

\s means a space or a new line

const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;

console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
4

You can .split() your string by spaces (\s+) into an array, and then use .includes() to check if the array of strings has your word within it:

const hasWord = (str, word) => 
  str.split(/\s+/).includes(word);
  
console.log(hasWord("phones are good", "on"));
console.log(hasWord("keep it on the table", "on"));

If you are worried about punctuation, you can remove it first using .replace() (as shown in this answer) and then split():

const hasWord = (str, word) => 
  str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/).includes(word);
  
console.log(hasWord("phones are good son!", "on"));
console.log(hasWord("keep it on, the table", "on"));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
3

You can split and then try to find:

const str = 'keep it on the table';
const res =  str.split(/[\s,\?\,\.!]+/).some(f=> f === 'on');
console.log(res);

In addition, some method is very efficient as it will return true if any predicate is true.

StepUp
  • 36,391
  • 15
  • 88
  • 148
1

You can use .includes() and check for the word. To make sure it is a word and not part of another word, verify that the place you found it in is followed by a space, comma, period, etc and also has one of those before it.

gkgkgkgk
  • 707
  • 2
  • 7
  • 26
0

A simple version could just be splitting on the whitespace and looking through the resulting array for the word:

"phones are good".split(" ").find(word => word === "on") // undefined

"keep it on the table".split(" ").find(word => word === "on") // "on"

This just splits by whitespace though, when you need parse text (depending on your input) you'll encounter more word delimiters than whitespace. In that case you could use a regex to account for these characters. Something like:

"Phones are good, aren't they? They are. Yes!".split(/[\s,\?\,\.!]+/)
Eelke
  • 2,267
  • 1
  • 22
  • 26
-2

I would go with the following assumptions:

  1. Words the start of a sentence always have a trailing space.
  2. Words at the end of a sentence always have a preceding space.
  3. Words in the middle of a sentence always have a trailing and preceding space.

Therefore, I would write my code as follows:

function containsWord(word, sentence) {
    return (
       sentence.startsWith(word.trim() + " ") ||
       sentence.endsWith(" " + word.trim()) ||
       sentence.includes(" " + word.trim() + " "));
}

console.log(containsWord("test", "This is a test of the containsWord function."));
S. Walker
  • 2,129
  • 12
  • 30
-2

Try the following -

var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
  console.log('Substring found !!')
} else {
  console.log('Substring not found !!')
}
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
Rem
  • 1
  • 2