Javascript从短代码字符串中提取属性

luk*_*mcd 2 javascript regex wordpress

我有一个 Javascript 应用程序,它从 WordPress 数据库中检索短代码。所以我最终可能会得到一个这样的变量:

var shortcode = '[wp-form id="1946" title="My Test Form"]';
Run Code Online (Sandbox Code Playgroud)

我希望使用纯 Javascript 来访问属性,以便我可以提取标题等。我想这将是某种形式或正则表达式和 split()。但到目前为止,我的努力因被空格分割而受挫。

任何想法都非常感谢。

小智 5

尝试使用此代码:

var shortcode = '[wp-form id="1946" title="My Test Form"]';    
var attributes = {};
shortcode.match(/[\w-]+=".+?"/g).forEach(function(attribute) {
    attribute = attribute.match(/([\w-]+)="(.+?)"/);
    attributes[attribute[1]] = attribute[2];
});
console.log(attributes);
Run Code Online (Sandbox Code Playgroud)

输出:

Object {id: "1946", title: "My Test Form"}
Run Code Online (Sandbox Code Playgroud)