11

I want to find the difference between two strings in Javascript.

Given two strings

 var a = "<div>hello</div><div>hi</div><div>bye/</div>";
 var b = "<div>hello</div><div>hi</div>";

The result should be "<div>bye</div>".

Like in formula:

var result = a - b;

& I need this implementation in Javascript (Is there any default method is available for this in JS??)

Can anyone help me out?

Nithya S
  • 127
  • 1
  • 1
  • 9
  • Already addressed here: https://stackoverflow.com/questions/8024102/javascript-compare-strings-and-get-end-difference – Menefee Mar 26 '18 at 18:16
  • 1
    Is this for a string or specifically for DOM nodes? And there's not enough details about what you expect. Is this only for a starts with b? If b is `
    hello
    bye
    ` does that mean a-b is `
    hi
    `? Regardless, I feel like this isn't the right approach to your problem.
    – Kevin Raoofi Mar 26 '18 at 18:20

3 Answers3

21

You can obtain the desired output with

var s = a.replace(b, '')

5

This seems like an x/y question. But in any case, I’ll try to help you out.

We want to find the location of b within a.

var start = a.indexOf(b);
var end = start + b.length;

Now put it together.

return a.substring(0, start - 1) + a.substring(end);
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
jojois74
  • 795
  • 5
  • 10
-1

var a = "<div>hello</div><div>hi</div><div>bye/</div>";
var b = "<div>hello</div><div>hi</div>";

c = a.substring(b.length)

console.log(c);
Smartniggs
  • 173
  • 2
  • 5
  • Your answer only works for cases where the `a` starts with `b`, if `b` is nested in `a`, this will not work. Although it works for the example given by the author, questions like this on SO should be answered generally – Samathingamajig Oct 19 '20 at 19:55