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

标签 javascript regex wordpress

我有一个 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/

相关文章:

javascript - 匹配javascript中的特定字符

php - 在publish_post WordPress上获取Yoast插件信息

html - 如何将选择按钮与条款和条件文本对齐在同一行

javascript - IE 11 中的 jQuery 1.8 不会在页面加载时触发图像加载事件

javascript - 如何通过复选框在模型的数组/内容上实现多个过滤器

"it does NOT start with KEYWORD1"的正则表达式

php - m 正则表达式模式修饰符

javascript - typescript :定义没有特定键和链对象的接口(interface)

javascript - 基础站点(6)javascript顺序

php - WP-联系表格 7 -- PHP