Home > Article > Web Front-end > JavaScript custom function implements method to find the longest common substring of two strings
The example in this article describes how to implement a JavaScript custom function to find the longest common substring of two strings. Share it with everyone for your reference, the details are as follows:
//查找两个字符串的最长公共子串 function findSubStr(s1,s2){ var S=sstr= "" ,L1=s1.length,L2=s2.length; if (L1>L2){ var s3=s1;s1=s2,s2=s3,L1=s2.length;} for ( var j=L1;j> 0 ;j--) for ( var i= 0 ;i<=L1-j;i++){ sstr = s1.substr(i,j); if (s2.indexOf(sstr)>= 0 ) return sstr; } return "" ; } document .writeln(findSubStr( "aaa3333" , "baa333cc" )); //aa333 document .writeln(findSubStr( "aaaX3333--" , "baa333ccX3333333x" )); //X3333