I’m looking for the most straighforward way to figure out which string was inserted somewhere into a known other string.
Here’s what I have to work with:
- I have an existing variable representing a particular string. For instance:
var originalString = "pineapple";
- I also have a second variable that represents the original string after a second, unknown string has been inserted somewhere inside the first string. For instance:
var updatedString = "piBicycleneapple";
Here’s my goal:
- I need some way to work backward to figure out which string was inserted into
originalString
to createupdatedString
.
Some examples:
- If
originalString = "pineapple"
and ifupdatedString = "piBicycleneapple"
, the desired result would be"Bicycle"
. - If
originalString = "pineapple"
and ifupdatedString = "pineapplepear"
, the desired result would be"pear"
.
Browser support:
I’m looking for a method that works in at least the current versions of Chrome, Firefox, and Safari. So all that is to say, if by chance you had wanted to share some fancy-pants latest-ECMAScript way of doing this, that’s not necessarily a dealbreaker (as long as CanIUse or the like can confirm that that technique works in modern browsers).
Other thoughts:
I’ve brainstormed this a l’il bit, and I suppose that I could maybe use a for loop to compare originalString
and updatedString
character by character and then—something something—profit? But I’m not totally sure about that middle part or even whether that general approach might be overthinking it?
2
Answers
This might work for you :
As @Barmar commented,
Note the potential ambiguity: if the inserted string has a part in common with the original string, you won’t be able to distinguish between different rotations of it without extra information.