我有一个 Javascript 应用程序,它从 WordPress 数据库中检索简码字符串。所以我最终可能会得到这样的变量:
var shortcode = '[wp-form id="1946" title="My Test Form"]';
我希望使用纯 Javascript 来访问属性,以便我可以提取标题等。我想这将是某种形式或正则表达式和 split()。但到目前为止,我的努力因被空格分割而受挫。
非常感谢任何想法。
最佳答案
尝试使用这段代码:
const shortcode = '[wp-form id="1946" title="My Test Form" empty=""]';
let attributes = {};
shortcode.match(/[\w-]+=".*?"/g).forEach(function(attribute) {
attribute = attribute.match(/([\w-]+)="(.*?)"/);
attributes[attribute[1]] = attribute[2];
});
console.log(attributes);
输出:
Object {id: "1946", title: "My Test Form", empty: ''}
关于Javascript 从短代码字符串中提取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37576843/