31

I have two strings.
String A: "The quick brown fox"
String B: "The quick brown fox jumps over the lazy dog."

String B will always contain string A verbatim. There will never be a "quick black fox" or a "quick and speedy brown fox".

How do I get a "String C" of the difference "jumps over the lazy dog."?

greybeard
  • 2,249
  • 8
  • 30
  • 66
Ian McCullough
  • 1,423
  • 4
  • 25
  • 36

9 Answers9

44

const A = "The quick brown fox"

const B = "The quick brown fox jumps over the lazy dog."

const diff = (diffMe, diffBy) => diffMe.split(diffBy).join('')

const C = diff(B, A)

console.log(C) // jumps over the lazy dog.
Mateja Petrovic
  • 3,799
  • 4
  • 25
  • 40
  • 1
    Good eye, Mateja, VERY elegant solution for the OPs problem. d-d-d-d-d-efinitely should be the accepted answer (with just one modification maybe): Since the OP didn't state however where within string A string B will occur (even though the example had it at the beginning), it would be good to examine B.split(A)[0] as well. – KevinHJ Jul 31 '18 at 01:26
  • What I meant was, A="the lazy dog", B="The quick brown fox jumps over the lazy dog", arr=B.split(A), console.log(arr[0] + arr[1]) // "The quick brown fox jumps over" – KevinHJ Aug 01 '18 at 00:49
  • 1
    Simply joining arr[0] and arr[1] will always give the difference whether the partial string is at the beginning, end, or middle. – KevinHJ Aug 01 '18 at 00:57
  • 1
    Great for guarenteed substrings, but does not work for middle-diffs. What about `diff("AAAAA", "AABAA")`? There is no exact match, and thus you will get no splits, returning the original string. Perhaps the wrong problem that OP, however. – mix3d Dec 04 '18 at 21:19
  • @mix3d What would you like `diff("AAAAA", "AABAA")` to return? – Mateja Petrovic Dec 05 '18 at 15:30
  • 1
    This also does not handle string with multiple whitespace characters – Hunter Monk Apr 15 '20 at 03:44
12

See the basic example below. This can easily be modified/extended for different behaviour.

var stringA = document.getElementById('string_a').textContent,
    stringB = document.getElementById('string_b').textContent,
    firstOccurrence = stringB.indexOf(stringA);

if(firstOccurrence === -1)
{
  alert('Search string Not found');
}
else
{
  var stringALength = stringA.length;
  var newString;

  if(firstOccurrence === 0)
  {
    newString = stringB.substring(stringALength);
  }
  else
  {
    newString = stringB.substring(0, firstOccurrence);
    newString += stringB.substring(firstOccurrence + stringALength);
  }

  document.getElementById('diff').textContent = newString;
}
<p>String A: <span id="string_a">The quick brown fox</span></p>
<p>String B: <span id="string_b">The quick brown fox jumps over the lazy dog</span></p>
<hr/>
<p>Difference: <span id="diff"></span></p>
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Ghost-Man
  • 2,179
  • 1
  • 21
  • 25
  • 1
    I used to be a computer science tutor (or, in the US, a 'TA'). This would be the only answer I'd award full marks to. It ought to be the accepted answer. – Michael Scheper Aug 19 '15 at 15:14
  • @MichaelScheper I agree, this should be the accepted answer, I have formatted for better readability and turned into runnable code snippet – doz87 Jan 23 '17 at 21:01
  • 1
    Nice one, @doz87! Suggestions for further improvement: use the identity operator instead of equality operator http://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons and camelCase variable names instead of ones with_underscores http://www.w3schools.com/js/js_conventions.asp But neither of these issues affect the correctness nor usefulness of this answer. – Michael Scheper Jan 24 '17 at 01:38
  • @MichaelScheper Absolutely agree with your suggestions, I'll admit.. I was being lazy :) but I've updated the answer now – doz87 Jan 24 '17 at 04:53
  • @doz87: I'm still seeing underscores and equality operators. Perhaps your changes didn't save? ☹ Again, it's not a big deal, but thanks for the effort—the more examples we create that follow good coding standards, the better all the code in the world will get. ☺ – Michael Scheper Feb 07 '17 at 00:22
10

If "String B will always contain string A verbatim", won't the following suffice?

var c = b.replace(a, "");
kc2001
  • 5,008
  • 4
  • 51
  • 92
8

You need to cross check each word to the other one.

var s1 = "The quick brown fox",
  s2 = "The quick brown fox jumped over the fence",
  string1 = new Array(),
  string2 = new Array(),
  diff = new Array(),
  longString;

string1 = s1.split(" ");
string2 = s2.split(" ");

if (s1.length > s2.length) {
  longString = string1;
} else {
  longString = string2;
}

for (x = 0; x < longString.length; x++) {
  if (string1[x] != string2[x]) {
    diff.push(string2[x]);
  }
}

document.write("The difference in the strings is " + diff.join(" "));
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
comu
  • 921
  • 1
  • 11
  • 29
7

comu's answer as a function...

function compareString( s1, s2, splitChar ){
    if ( typeof splitChar == "undefined" ){
        splitChar = " ";
    }
    var string1 = new Array();
    var string2 = new Array();

    string1 = s1.split( splitChar );
    string2 = s2.split( splitChar );
    var diff = new Array();

    if(s1.length>s2.length){
        var long = string1;
    }
    else {
        var long = string2;
    }
    for(x=0;x<long.length;x++){
        if(string1[x]!=string2[x]){
            diff.push(string2[x]);
        }
    }

    return diff;    
}
compareString( "?Yo=dude", "?Yo=Dude&do=roby", "&" ).join('\n');
compareString( "?Yo=Dude", "?Yo=Dude&do=roby", "&" ).join('\n');

Note: this answer solves the issue of finding extra query parameters (based on another query string), and is not an exact answer for the OP.

chim
  • 8,407
  • 3
  • 52
  • 60
  • 1
    That's quite an overengineered solution!! ~Ghost-Man's solution is at least an order of magnitude more efficient! http://stackoverflow.com/a/8024608/1450294 – Michael Scheper Aug 19 '15 at 15:10
  • 2
    That's a fair comment @Michael I haven't answered the original question, but posted a solution to the problem that I had at the time. I think I must have done this as this was the problem I was trying to solve and it was comu's answer that helped me, so I posted the code I used. I'll update my answer to reflect that it doesn't answer the question exactly. – chim Aug 20 '15 at 08:34
  • 2
    I commend your StackOverflow integrity. :-) – Michael Scheper Aug 20 '15 at 14:57
4

Check out this site for a wonderful API to see the difference between strings: google-diff-match-patch You might need to check the UI according to your need though.

akshay
  • 472
  • 4
  • 14
1
const str1 = "The quick brown fox jumps over the lazy dog.";
const str2 = "he quick brown fox";

res = Str1.split(str2).join('');
greybeard
  • 2,249
  • 8
  • 30
  • 66
Dhole Hari
  • 11
  • 1
  • 1
  • (Try pasting that into a Python interpreter.) (Some interpretation of `end difference` - not that the question was exemplary consistent.) – greybeard Jun 04 '21 at 05:04
0

I found the simple way.

Here is the code:

var t1 = "The quick brown fox";
var t2 = "The quick brown fox jumps over the lazy dog.";
var indxFoundStart = t2.search(t1); //first index of the position of t1 found in t2 (not use but you can print for sure)
var indxFoundEnd = t1.length; //last index of t1 found in t2
var textCompareLen = t2.length; // length of the longer string

// You can add the condition to verify which text is shorter, which text is longer if you do not want to fixed in t1 and t2
document.write("difference string is: " + t2.substring(indxFoundEnd, textCompareLen));

I have try with 2 sample, the text with space and the text without space and it work fine.

Absolutely, I have try with your example, and it work fine too.

Pim H
  • 223
  • 2
  • 8
0

You can just use String.prototype.replace() :

var string1 = "The quick brown fox"
    
var string2 = "The quick brown fox jumps over the lazy dog."
    
var diff = ''
    
diff = string2.replace(string1, '')
    
console.log(diff)