Is there any simpler way (ideally from a builtin I missed from the doc) to retrieve the common substring between the end of a string and the beginning of another string? For example abcdef and defghi should return def.
abcdef
defghi
=========
def
My current implem:
const a = "abcdef";
const b = "defghi";
function findCommonEndStart(a, b) {
let common = "";
for (let i = 1; i <= a.length; i++) {
const sub = a.slice(-i, a.length);
if (b.startsWith(sub)) {
common = sub;
}
}
return common;
}
console.log(findCommonEndStart(a, b));
Here how I did it.
let a = "abdef";
let b = "defdklc";
function func(x, y) {
for (i in x) {
if (x.substr(-i, x.length) == y.substr(0, i)) {
console.log(x.substr(-i, x.length))
}
}
}
func(a, b)
Seems like you're looking for simple regular expression:
let str = 'abcdef defghi';
let find = str => str.match(/(\w+)\b.+\b(?:\1)/m)?.[1];
let result = find(str); // result = 'def'