Reputation: 814
Let's just say I have two strings, a
& b
.
var a = '[email protected]';
var b = 'yahoo12345556';
What I am expecting is result would be yahoo
but using a.indexOf(b)
would give me -1
.
If I change b
to yahoo
& do a.indexOf(b)
, it obviously wouldn't give me -1
.
Should I match characters in a loop instead? But the two strings aren't of equal length. It's also important that the characters should be in sequence, I am not looking for occurrence of characters.
Upvotes: 0
Views: 81
Reputation: 507
You might be able to use recursion to solve this problem:
function findLongestCommon (a, b, len) {
for (var i = 0; i < a.length-1; i=i+len) {
var sub = a.substring(i, len)
if (len == 0){
return "";
}
else if (sub.indexOf(b) != -1) {
return a;
}
else{
return findLongestCommon(a, b, len-1);
}
}
By calling findLongestCommon(a, b, a.length) you will be able to go through every combination of letter starting with the largest (the whole string) to the smallest (one letter) and if no letter is found it will return empty string.
Upvotes: 0
Reputation: 4833
It seems your are looking for Longest Common Substring problem. Here is a good javascript implementation with explanations.
Upvotes: 1