Epic3lite Epic3lite - 1 year ago 74
Javascript Question

Compare two strings and output result where both are equal

I have two strings, and I want to output one string where both give the same values.

var string1 = "ab?def#hij@lm";
var string2 = "abcd!f#hijkl]";

//expected output would be "abcdef#hijklm"

I have thought a way to do this would be to assign each character to an array, then compare each character individually but that seems inefficient, as I'm going to pass this through strings with tens of thousands of characters.

Any help is appreciated, doesn't have to be code, just to guide me in the general direction.

Answer Source

You could use replace with its callback argument:

string1.replace(/[^a-z]/ig, (_, i) => string2[i])

var string1 = "ab?def#hij@lm";
var string2 = "abcd!f#hijkl]";

var res = string1.replace(/[^a-z]/ig, (_, i) => string2[i]);

This will favour letters, but if both strings have different letters at the same position, the character in string1 will get precedence. On the other hand, if both have a non-letter, the one from string2 will be taken.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download