write a function that returns the longest common substring between two given strings . each string is of maximum length 100. consider using existing string methods like substr and find . note that find returns a large positive number instead of -1

Respuesta :

Function that returns the longest common substring, between two given strings:

function longestCommonSubstring(str1, str2) {

 var longest = "";

 var current = "";

 for (var i = 0; i < str1.length; i++) {

   for (var j = 0; j < str2.length; j++) {

     if (str1.charAt(i) === str2.charAt(j)) {

       current += str1.charAt(i);

       if (current.length > longest.length) {

         longest = current;

       }

     } else {

       current = "";

     }

   }

 }

 return longest;

}

Code Explanation:

  • We initialize two variables longest and current to empty strings.
  • We iterate over the first string str1 using a for loop.
  • For every character in str1, we iterate over the second string str2.
  • If the characters at the current indices of both the strings match, we append the character to the current string and compare its length with the longest string. If it is greater, we update the longest string.
  • If the characters do not match, we reset the current string to an empty string.

Learn more about programming:

https://brainly.com/question/14277907

#SPJ4