UNPKG

1.14 kBJavaScriptView Raw
1function rawAttributes(rawAttrs) {
2 const attrs = {};
3 if (rawAttrs) {
4 // const re = /\b([a-z][a-z0-9\-]*)(?:\s*=\s*(?:("[^"]*")|('[^']*')|(\S+)))?/ig;
5 const re = /\b([a-z][a-z0-9\-]*)(?:\s*=\s*("(?:[^"]*)"|'(?:[^']*)'|(?:\S+)))?/ig;
6 let match;
7 console.debug('0000', rawAttrs);
8 while (match = re.exec(rawAttrs)) {
9 console.debug('1111', match[1]);
10 const v = match[2] || '';
11 console.debug('2222', v.replace(/^['"]/, '').replace(/['"]$/, ''));
12 attrs[match[1]] = v.replace(/^['"]/, '').replace(/['"]$/, '');
13 }
14 }
15 return attrs;
16}
17
18function attr2str(attrs) {
19 return Object.keys(attrs).map((name) => {
20 const val = attrs[name];
21 if (val === undefined || val === null) {
22 return name;
23 } else {
24 return name + '=' + val
25 }
26 }).join(' ')
27}
28
29function main() {
30 let r;
31 // r = rawAttributes('a="1"');
32 // r = rawAttributes('a=\'1\'');
33 // r = rawAttributes('a=');
34 // r = rawAttributes('a');
35 // r = rawAttributes('a=1');
36 // r = rawAttributes('a=aa b="bb" c= \'cc\' d="\'dd\'" e=e\'e\"e f');
37 r = attr2str({
38 a: 'aa',
39 b: '"bb"',
40 c: "'cc'",
41 d: "'dd'",
42 e: `e'e"e`,
43 f: null
44 });
45 console.debug(r);
46}
47
48main();
49