Home > Web Front-end > JS Tutorial > JavaScript custom function implements method to find the longest common substring of two strings

JavaScript custom function implements method to find the longest common substring of two strings

高洛峰
Release: 2016-12-05 13:34:08
Original
2553 people have browsed it

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
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template