Find common substring of > 1 character length between two strings in JS

As per title, I need to find the common substring between two strings, which is longer than 1 character (so one that’s one character long doesn’t count).

I am trying to firstly compare two strings and if their characters match, to return true. Else, to return false. So far I have this code:

function SubstringTest(str1, str2){      for ( let i = 0; i < str1.length; i++) {      for (let j = 0; j < str2.length; j++) {                if ((str1[i]) === (str2[j])) {                    return true        } else {          return false        }      }    }   } SubstringTest("something", "home") 

but I can’t understand why it doesn’t work. Can anybody point me in the right direction? Thanks.

Add Comment
2 Answer(s)

This is the bruteforce, non-optimal solution:

let commonSubstring = (str1, str2, minLen=1) => {      let best = { len: 0, off1: null, off2: null };      for (let off1 = 0; off1 < str1.length - minLen; off1++) {     for (let off2 = 0; off2 < str2.length - minLen; off2++) {              // Holds the number of characters that match       let maxLen = Math.min(str1.length - off1, str2.length - off2);       let len = 0;       while (len < maxLen && str1[off1 + len] === str2[off2 + len]) len++;              // Store this result if it's the best yet       if (len > best.len) best = { len, off1, off2 };            }   }      // We can now assert that str1.slice(best.off1, best.len) === str2.slice(best.off2, best.len)   return best.len >= minLen ? str1.slice(best.off1, best.off1 + best.len) : null;    };  let tests = [   [ 'mustard', 'hustler' ],   [ 'lemon', 'harlem' ],   [ 'marshmallow', 'hollow' ],   [ 'marshmallow', 'marshal' ],   [ 'jefferson', 'jeffery' ] ];  console.log('Examples:'); for (let [ str1, str2 ] of tests) {   console.log(`Strings "${str1}" and "${str2}" share substring "${commonSubstring(str1, str2, 2)}"`); }

The idea is to iterate all pairings of offsets within str1 and str2. Eventually we’ll arrive at the offsets where the longest sequence of shared characters occurs.

Note that I provided minLen as a parameter. You can set it to 2 if you want to discard any results less than 2 characters long.

Answered on July 16, 2020.
Add Comment
   function SubstringTest(str1, str2){        var matchingText = "";        for ( let i = 0; i < str1.length; i++) {             if(str1[i] == str2[i]){                 matchingText+= str1[i];             }        }         if(matchingText.length > 0)             return true;         return false;    } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.