arraysstringsearch

Check amount of array items contained in string


I've been wondering how to check the amount of items of an array a string has for quite a while now, since I have many cases I need that sort of function.

Let's say this is my code:

let array = [
    "foo",
    "bar"
]
function funnyFunction(string) {
    // code to do what question asks
}
console.log(funnyFunction("Have you ever wondered why they use foo in programming examples? And sometimes they use foo and bar when there's an amount of something. And I still don't know what foobar even means."))

In this case, I would want funnyFunction() to return an integer. funnyFunction() wouldn't search for words, it would search the entire string, disregarding spaces or anything like that, so doing funnyFunction("foo bar") and funnyFunction("foobar") would return the same value, 2.

And in the example code, the result should be 5.

Any idea how to approach that idea?


Solution

  • Quick and dirty solution

    Use the indexOf and substr string functions:

    let array = [
        "foo",
        "bar"
    ];
    
    function funnyFunction(string) {
      const strlen=string.length;
      let ocurrency=0,index=0,start=0,wordlen=0;
      for(let i=0;i<array.length;i++){
        index=0;
        start=0;
        wordlen=array[i].length;
        while(index>-1&& start<strlen-wordlen){
          index=string.substr(start,strlen).indexOf(array[i]);
          if(index>-1){
            ocurrency++;
            start+=index+wordlen;
          }
        }
      }
      return ocurrency;
    }
    
    console.log(funnyFunction("Have you ever wondered why they use foo in programming examples? And sometimes they use foo and bar when there's an amount of something. And I still don't know what foobar even means."));