Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to pull attributes from shortcode string

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.

like image 507
lukemcd Avatar asked May 31 '26 21:05

lukemcd


1 Answers

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: ''}
like image 80
Sergey Khalitov Avatar answered Jun 02 '26 10:06

Sergey Khalitov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!