UNPKG

975 BJavaScriptView Raw
1var parse = require('inline-style-parser');
2
3/**
4 * Parses inline style to object.
5 *
6 * @example
7 * // returns { 'line-height': '42' }
8 * StyleToObject('line-height: 42;');
9 *
10 * @param {String} style - The inline style.
11 * @param {Function} [iterator] - The iterator function.
12 * @return {null|Object}
13 */
14function StyleToObject(style, iterator) {
15 var output = null;
16 if (!style || typeof style !== 'string') {
17 return output;
18 }
19
20 var declaration;
21 var declarations = parse(style);
22 var hasIterator = typeof iterator === 'function';
23 var property;
24 var value;
25
26 for (var i = 0, len = declarations.length; i < len; i++) {
27 declaration = declarations[i];
28 property = declaration.property;
29 value = declaration.value;
30
31 if (hasIterator) {
32 iterator(property, value, declaration);
33 } else if (value) {
34 output || (output = {});
35 output[property] = value;
36 }
37 }
38
39 return output;
40}
41
42module.exports = StyleToObject;