javascriptstringloops

Check if the end of one string matches the begining of another string


I have two strings:

let string1 = "Some text here";
let string2 = "text here as well";

I would like to check if the end part of string1 matche the start of string2.

I'm outputting string1 + string2. In my case I don't want to print the same words twice. For example, I don't want to print "Some text heretext here as well".

How to I check for this? I have tried startsWith/endsWith and a loop by spiting the string from space. But i don't think my approach is correct as the matching part of strings can vary in length.

Strings can also contain dashes. For example it can be like:

let string1 = "Some-text here";
let string2 = "text here as well";

In the above example the ideal output will be "Some-text here as well".


Solution

  • You can use String.substring to get substrings of both input values, from the end of string1 and the start of string2. If these are the same, we've found our overlap.

    let string1 = "Some-text here";
    let string2 = "text here as well";
    
    let overlap = null;
    for(let i = 1; i <= string1.length; i++) {
         if (string1.substring(string1.length - i) === string2.substring(0, i)) {
             overlap = string2.substring(0, i);
             break;
         }
    }
    
    console.log('Overlap:', overlap);
    
    let concatenated = string1.replace(overlap, '') + string2;
    
    console.log('string1 + string2:',concatenated);