I’m trying to come up with an efficient way to overwrite 2 strings that look like this:
str1 = "width=800,height=600,resizable=no,titlebar=no";
str2 = "width=100,height=100";
In the above example, str2 should overwrite str1 to produce str3:
str3 = "width=100,height=100,resizable=no,titlebar=no";
In my tests, I turned str2 into an array and tested each key against a match in str1.
Can anyone think of a more efficient way to write this:
str1 = "width=800,height=600,resizable=no,titlebar=no";
str2 = "width=100,height=100";
sArray = str2.split(",");
for( var i = 0; i < sArray.length; i++ ) {
var key = sArray[i].match(/(\w+)=/gi).toString().replace("=", ""),
in_str1 = str1.search(key),
replace_pattern = new RegExp(key+"=(\\w+)", "gi");
if(in_str1 !== -1){
str1 = str1.replace(replace_pattern, sArray[i]);
} else {
str1 = str1 + "," + sArray[i];
}
}
Here’s a pretty terse regex-based solution:
It works by prepending the overriding string to the overridable string, then repeatedly stripping out duplicates that occur later in the joined string until there aren’t any.
A little more care will be needed if either string could be empty, or if any kind of escaping is permitted, or if the keys can be named other than with letters only.