I have a Javascript application which retrieves shortcode stings from a WordPress database. So I may end up with a variable like this:
var shortcode = '[wp-form id="1946" title="My Test Form"]';
I am looking to use pure Javascript to access the attributes so I can extract the title, etc. I imagine this will be some form or regex and split(). But so far my efforts get frustrated by splitting by whitespace.
Any ideas greatly appreciated.
Try to use this code:
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);
Output:
Object {id: "1946", title: "My Test Form", empty: ''}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With