Search for substring using JavaScript function
P粉098979048
P粉098979048 2023-09-13 11:04:31
0
1
492

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粉098979048
P粉098979048

reply all(1)
P粉958986070

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"));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template