Reputation: 14780
I have the following two cssText strings:
var s1 = "text-align: right; font-weight: bold;";
var s2 = "text-align: left; color: #000";
I need to get string that consists of merged properties from them:
var result = merge(s1, s2);
result:
"text-align: left; font-weight: bold; color: #000;"
Upvotes: 2
Views: 532
Reputation: 3
as noted above,
element.style.CSStext = s1+s2
is best for direct CSS use ... however,
result = eval ( "({"+ (s1+s2) . replace(/ *([^:;]+) */g,"'$1'") . replace(/;/g,",")+ "})" ) /* make object literally */
. toSource() /* lucky if using FF browser */
. replace(/'|"|\({|}\)/g,"")
. replace(/,/g,";") /* massage result */
Upvotes: 0
Reputation: 3162
Here is a solution that takes an array of strings and overrides any properties if it was there previously:
function merge(strings){
var result = {}
for(var i in strings){
var cssProperties = createObject(strings[i])
for(var attr in cssProperties) {
result[attr] = cssProperties[attr];
}
}
var s = ''
for(var attr in result){
s += attr + ':' + ' ' + result[attr] + '; ';
}
return s.trim()
}
function createObject(s1){
var obj = {};
var properties = s1.split(';');
for(var i=0; i<properties.length; i++){
var property = properties[i].split(':');
if(property.length == 2){
console.log(property[1]);
obj[property[0].trim()] = property[1].trim();
}
}
return obj;
}
merge(["text-align: right; font-weight: bold;", "text-align: left; color: #000"])
This solution will work with arbitrary number of strings, not just two.
Upvotes: 1
Reputation: 8022
write a function to make an object out of the string, giving you e.g obj.fontWeight which would say "bold".
make an object from each string using the above function.
make a new object using Object.create which takes the first object as the proto arg and the second object as the properties map. This gives an object where any properties in the second object override ones in the first, but where properties not on the second but on the first come through, thus implementing the merge part of the algorithm.
write a function that turns all properties of the object you made in 3 back into a string, remember you need properties on the prototype as well do don't us hasOwnProperty in the for in loop.
you'll need to handle going from - form to camel case which is pain but easy enough to do.
Upvotes: 0
Reputation: 1043
You can create a associative array (or map) out of the strings and merge both. This will give you merged list of properties.
Otherwise, if you are just looking to apply all these properties to an element, even though you have two values of same property, second one will take precedence.
Upvotes: 3