JSFiddle - React, Tailwind, and code Playground

by Wentz Wu

HTML

<a href="https://stackoverflow.com/questions/3898083/find-longest-repeating-substring-in-javascript-using-regular-expressions" target="_black">maxRepeat</a>

JavaScript

function maxRepeat(input) {
  var reg = /(?=(^(.+)(?:.*?\2)+))/g;
  var sub = ""; //somewhere to stick temp results
  var maxstr = ""; // our maximum length repeated string
  reg.lastIndex = 0; // because reg previously existed, we may need to reset this
  sub = reg.exec(input); // find the first repeated string
  while (sub != null) {
    if (sub[2].length > maxstr.length) {
      maxstr = sub[2];
    }
    sub = reg.exec(input);
    reg.lastIndex++; // start searching from the next position
  }
  return maxstr;
}


console(maxRepeat("abcd abcdabcd").length);