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:
Output:
Okay, even though I’m late to the party I’m going to throw an answer in. I’m surprised nobody complained “you can’t parse with just a regular expression!” I guess this used to be a much more fashionable comment to make . Anyways, I think it’s perfectly reasonable to use just a regex and see some reasonable attempts already given.
However, if you want to really parse the tag, here’s a quick parser I whipped up.
I’m sure this has bugs, but I got it to work with your case, and some cases the other answers couldn’t handle. Unless shortcodes get really intense, I’d just stick with a regex. But if you encounter stuff like unquoted attribute values and empty attributes this might work for you.
Don’t try to use
String.prototype.split
in this case, describe an attribute with its value and build a pattern to match them usingRegExp.prototype.exec
:can be done using regex simply