title: bruteforce string matching javascript
body: <pre><code>  function search(pattern, text) {
              var M = pattern.length;
              var N = text.length;
              for (var i = 0; i &lt; N - M; i++) {
                  var j =0;
                  while (j &lt; M) {
                      if (text.charAt(i + j) != pattern.charAt(j)) {break;}
                  }
                  if (j == M) {return i;}
              }
              return -1;
          }
  
          console.log(search("rf", "jdsrfan"));
  </code></pre>
  
  <p>I want to make an brute-force string matching algorithm in JavaScript. Can anyone tell me  whats wrong with above code?</p>
  
  <p>I did fixed it myself fixed code as follows:</p>
  
  <pre><code>// return offset of first match or -1 if no match
  function bruteForcePatternSearch(sPattern, sText) {
      var M = sPattern.length,
          N = sText.length;
      for (var i = 0; i &lt;= N - M; i++) {
          var j=0;
          while (j &lt; M) {
              if (sText.charAt(i+j) !=sPattern.charAt(j)){
                  break;
                  }
          j++;
              }
          if (j == M) {return i;}            // found at offset i
      }
      return -1;                            // not found
  }
  
  bruteForcePatternSearch("abracadabra","abacadabrabracabracadabrabrabracad");
  </code></pre>