javascript - Select from two strings where they differ -
my page receives 2 strings:
var string1 = "_some_specification_abc_defgh_end_code"; var string2 = "_some_specification_34_kj_w7_end_code";
and want take differ display later title
function selectrelevantinfo (string1, string2) { // don't know if regex here };
it should give abc_defgh string1 , 34_kj_w7 string2.
how can achieve it? in advance.
here's attempt, few tests make sure when prefix/postfix non-existent, or if both strings, etc.
it's similar in spirit pablo's code, in searches front , of strings, rather using indexof
@ each iteration (accidentally quadratic), scalar character comparisons. function return object containing prefix , postfix both input strings stripped of these.
function findprepostfix(a, b) { var minlength = math.min(a.length, b.length); // important initialization , prefix search var prelen = minlength; (var = 0; < minlength; i++) { if (a[i] !== b[i]) { prelen = i; break; } } // similar search postfix search plus important initialization var postlen = minlength - prelen; (var = 0; < minlength - prelen; i++) { if (a[a.length - - 1] !== b[b.length - - 1]) { postlen = i; break; } } return { : a.substring(prelen, a.length - postlen), b : b.substring(prelen, b.length - postlen), prefix : a.substring(0, prelen), postfix : a.substring(a.length - postlen, a.length) }; } function display(a, b) { $("body").append("<p>“" + + "” vs “" + b + "”: <tt>" + json.stringify(findprepostfix(a, b)) + "</tt></p>"); } // display = function(a, b) { console.log(findprepostfix(a, b)) }; display('_some_specification_abc_defgh_end_code', '_some_specification_34_kj_w7_end_code'); display("abc123", "123"); display("abc", "abc123"); display("abc", "def"); display("abc", "abc");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Comments
Post a Comment