1

Is it possible to merge two strings in JavaScript so that all the similarities are kept only keeping the differences.

For example

var string1 = "I am a sentence";
var string2 = "I am a dancer";

var string3 = function(string1, string2);
string3 = "I am a sentence dancer";

The similarities between the were preserved but the differences are added onto the string.

The reason I am asking is that I have a website application where the user can either edit the page through contenteditable or the code itself through a <textarea></textarea>. And so if they edit both, it submits both changes.

Ignatius_Gim
  • 582
  • 2
  • 5
  • 21
  • Does it matter that the result could be completely nonsensical? – Alex K. Feb 18 '14 at 17:43
  • @AlexK. No it does not. – Ignatius_Gim Feb 18 '14 at 17:44
  • 1
    Your example is a bit arbitrary, as it's not 100% clear to me how the two strings should be combined in all circumstances – jordancpaul Feb 18 '14 at 17:46
  • algorithms for the [longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem) (base of most diff tools) will help you on that one – collapsar Feb 18 '14 at 17:49
  • How complicated would the text get. How would the following two strings merge? "I was a skater but am a dancer". and "I am a dancer but was a skater." – jing3142 Feb 18 '14 at 17:55
  • pretty complicated, but I've decided to go with Aidas Bendoraitis's answer since it gets what I need done. Just wondering how to run js function when a div is changed – Ignatius_Gim Feb 18 '14 at 17:57

3 Answers3

2

I would rather update the textarea data, when content editable is edited, and update content editable, when textarea is edited. This way, you would be sure, that all edits are saved for the user.

Aidas Bendoraitis
  • 3,965
  • 1
  • 30
  • 45
0

I think it can be as a variant.

function merge(str, str2){
    var a = str.split(" ");
    str2.split(" ").forEach(function(i, index){
        var len = a.filter(function(item){return item == i;}).length;
        if(len == 0) a.push(i);
    });
    return a.join(" ");
}

console.log(merge("I am a sentence","I am a dancer"));
// result "I am a sentence dancer"

Play with demo!

Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
0

If you're looking to merge at the character level (rather than just at the word level), then you need a more general solution. The levenshtein distance is the number of changes (replacements, additions) needed to turn one sting into another. For an example, try this site http://andrew.hedges.name/experiments/levenshtein/

There are a number of levenshten algorithm examples which can be found on the web. You will need to modify them slightly to not just report the changes between the two strings, but use them to merge the two together.

jordancpaul
  • 2,954
  • 1
  • 18
  • 27