-4

I am trying to check if a string contains a specific word only once.

Here is my attempt, but it's not working:

const test = "hello this is a new string hello";
// if hello contains only once then true otherwise false;

// here is my try but
let containshello = test.includes("hello");
console.log(containshello);
Ivar
  • 6,138
  • 12
  • 49
  • 61
Mamunur Rashid
  • 1,095
  • 17
  • 28
  • Of course it is not working, because your attempt doesn't contain anything that actually checks how many times it was found. Hint: `includes` takes an optional second parameter for the position it should start searching from. – CBroe Aug 08 '22 at 07:52
  • 2
    I would use `indexOf` and `lastIndexOf` for this to begin with though. – CBroe Aug 08 '22 at 07:53
  • 1
    Does this answer your question? [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – cMarius Aug 08 '22 at 07:53

4 Answers4

2

Here's an approach using filter

const containsWordOnce = (str, searchKey) => {
  return str.split(' ').filter((word) => word === searchKey).length === 1;
};

const test = "hello this is a new string hello";
console.log(containsWordOnce(test, "hello"));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
1

Use 'regex match' to get the occurrence of a substring in a string.

const test = "hello this is a new string hello";
console.log(test.match(/hello/gi)?.length); // 2 : 'hello' two times
console.log(test.match(/new/gi)?.length);  // 1 : 'new' one time
console.log(test.match(/test/gi)?.length); // undefined : 'test' doesn't exist in string.

I have used 'g' for Global checking and 'i' for ignoring the case.

If you want to create 'Regex' object create like this:

const test = "hello this is a new string hello";
const regx = new RegExp('hello', 'gi') // /hello/gi
console.log(test.match(regex)?.length);
Art Bindu
  • 769
  • 4
  • 14
0

const test = "hello this is a new string hello";
const findString = "hello"

console.log(test.split(findString).length-1 === 1)
Nikita Aplin
  • 367
  • 2
  • 10
-1

I would just use a regular expression and use the match method on the string you would like to search using the "i" and "g" flag. Below is an example function although there are most likely better ways.

function containsWordOnce(string, word) {
    const re = new RegExp(word, 'ig');
    const matches = string.match(re);
    return matches.length === 1;
}

Just plug in your string and word your trying to find.