Nithya S
Nithya S

Reputation: 127

Subtract two strings in jS

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?

Upvotes: 11

Views: 37424

Answers (3)

Smartniggs
Smartniggs

Reputation: 300

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);

Upvotes: -1

jojois74
jojois74

Reputation: 805

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);

Upvotes: 5

user7956371
user7956371

Reputation:

You can obtain the desired output with

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

Upvotes: 22

Related Questions