在 JavaScript 中解析短代码 [英] Parse shortcodes in JavaScript
本文介绍了在 JavaScript 中解析短代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来解析字符串中的短代码,该方法将在对象数组中返回它们的 id 和值,如下所示:
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
}
]
推荐答案
复杂的解决方案:
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));
这篇关于在 JavaScript 中解析短代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文