首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析JavaScript中的快捷码

解析JavaScript中的快捷码
EN

Stack Overflow用户
提问于 2017-10-27 04:52:13
回答 1查看 502关注 0票数 0

我正在寻找一种解析字符串中的快捷码的方法,它将返回对象数组中的in和值,如下所示:

代码语言:javascript
复制
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
 }
]
EN

回答 1

Stack Overflow用户

发布于 2017-10-27 05:24:23

复杂的解决方案:

代码语言:javascript
复制
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));

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46963590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档