解析JavaScript中的短代码

时间:2017-10-26 20:52:13

标签: javascript regex

我正在寻找一种方法来解析字符串中的短代码,这将在一个对象数组中返回它们的ID和值,如下所示:

var str = 'First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in an array of objects like below';
var obj = parseShortcodes(str);

// obj now equals:

[
 {
  id: 'fraction',
  num: 1,
  denom: 2
 },
 {
  id: 'square-root',
  content: 456
 }
]

1 个答案:

答案 0 :(得分:1)

复杂的解决方案:

var parseShortcodes = function(str){
    var regex = /\[\S+(?:\s+[^="]+="[^"\]\s]+")+\]/g,
	m, obj, result = [];
		
	while ((m = regex.exec(str)) !== null) {
	    if (m.index === regex.lastIndex) {
		regex.lastIndex++;
	    }
	    m = m[0].slice(1, -1).split(/\s+/);
	    result.push(m.reduce(function(r, s){ 
	        var pair = s.split('=');
		r[pair[0]] = +pair[1].slice(1,-1);
		return r;
	    }, {id: m.shift()}));		
	}
	
	return result;
};

var str = `First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in an object like below'`;

console.log(parseShortcodes(str));