How to merge two strings based on shared suffix and prefix in JavaScript

1 Answer

0 votes
function mergeOnOverlap(a, b) {
    const lenA = a.length;
    const lenB = b.length;

    const maxPossibleOverlapLen = Math.min(lenA, lenB);

    let overlap = 0;

    // Try longest overlap first
    for (let len = maxPossibleOverlapLen; len > 0; len--) {
        if (a.slice(lenA - len) === b.slice(0, len)) {
            overlap = len;
            break;
        }
    }

    return a + b.slice(overlap);
}

const a = "fantasy time travel technology";
const b = "technology extraterrestrial life";

console.log(mergeOnOverlap(a, b));



/*
run:

fantasy time travel technology extraterrestrial life

*/

 



answered Jan 24 by avibootz
...