Home  >  Q&A  >  body text

Search for substring using JavaScript function

I want to write a code in JavaScript language that can search for the number of repetitions of letters in a word, like this code, but in a shorter way o(n).

function naiveSearch(long, short){
    var count = 0;
    for(var i = 0; i < long.length; i++){
        for(var j = 0; j < short.length; j++){
           if(short[j] !== long[i+j]) break;
           if(j === short.length - 1) count++;
        }
    }
    return count;
}
naiveSearch("lorielol loled", "lol")

P粉098979048P粉098979048424 days ago487

reply all(1)I'll reply

  • P粉958986070

    P粉9589860702023-09-14 00:42:16

    Use the .substring() or .slice() method instead of nested loops.

    function naiveSearch(long, short) {
      var count = 0;
      for (var i = 0, limit = long.length - short.length; i < limit; i++) {
        if (long.substring(i, i + short.length) == short) {
          count++;
        }
      }
      return count;
    }
    
    console.log(naiveSearch("lorielol loled", "lol"));

    reply
    0
  • Cancelreply