Parse shortcodes in JavaScript [closed]

谁说胖子不能爱 提交于 2021-02-05 12:26:29

问题


I'm looking for a way to parse shortcodes in a string, which will return their ids and values in an array of objects like the following:

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:


Complex solution:

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));


来源:https://stackoverflow.com/questions/46963590/parse-shortcodes-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!