August 4, 2017

Extract all wordpress shortcode in jQuery object

Extract all wordpress shortcode in jQuery object from the wordpress editer whose html id is #content.

This supports same level and hierarchical both.

See in fiddle

https://jsfiddle.net/shakalya/jswe18kL/

 

<script>

jQuery(function() {

var pageContent = jQuery(‘#content’).html();
var data = {};

var data = parseShortCode(pageContent);
console.log(data);
function parseShortCode(shortCode) {
var regex_for_match = /\[([\w-]+)([^]*?)(\/?)\](?:([^]*?)\[\/\1\s*\])?/g;
var count = 0;
var s=[];

while ((singleMatch = regex_for_match.exec(shortCode)) != null) {

//console.log(singleMatch);
innerContent = singleMatch[4];

var re = /(\s+|\W)|(\w+)/g;
var match;
var token;
var curAttribute = ”;
var quoteChar;
var mode = ‘NOT STARTED’;
var parsedValue = {
name: ”,
attributes: {},
content: ”,
parsedContent:”
};

while ((match = re.exec(singleMatch)) != null) {

token = match[0];

switch (mode) {

case ‘NOT STARTED’:
if (token == ‘[‘) {
mode = ‘GETNAME’;
}
break;

case ‘GETNAME’:
if (!(/\s/.test(token))) {
if (token == “]”){
mode = ‘COMPLETE’;
}else{
parsedValue.name += token;
}
} else if (parsedValue.name) {
mode = ‘PARSING’;
}
break;

case ‘PARSING’:
if (token == “]”) { mode = ‘COMPLETE’; }
else if (token == “=”) {
if (!curAttribute) throw (‘invalid token: “‘ + token + ‘” encountered at ‘ + match.index);
else mode = ‘GET ATTRIBUTE VALUE’;
}
else if (!/\s/.test(token)) {
curAttribute += token;
} else if (curAttribute) {
mode = ‘SET ATTRIBUTE’
}
break;

case ‘SET ATTRIBUTE’:
// these are always from match[1]
if (/\s/.test(token)) { parsedValue.attributes[curAttribute] = null; }
else if (token == ‘=’) { mode = ‘GET ATTRIBUTE VALUE’; }
else { throw (‘invalid token: “‘ + token + ‘” encountered at ‘ + match.index); }
break;
case ‘GET ATTRIBUTE VALUE’:
if (!(/\s/.test(token))) {
if (/[“‘]/.test(token)) {
quoteChar = token;
parsedValue.attributes[curAttribute] = ”;
mode = ‘GET QUOTED ATTRIBUTE VALUE’;
} else {
parsedValue.attributes[curAttribute] = token;
curAttribute = ”;
mode = ‘PARSING’;
}
}
break;

case ‘GET QUOTED ATTRIBUTE VALUE’:
if (/\\/.test(token)) { mode = ‘ESCAPE VALUE’; }
else if (token == quoteChar) {
mode = ‘PARSING’;
curAttribute = ”;
}
else { parsedValue.attributes[curAttribute] += token; }
break;

case ‘ESCAPE VALUE’:
if (/\\'”/.test(token)) { parsedValue.attributes[curAttribute] += token; }
else { parsedValue.attributes[curAttribute] += ‘\\’ + token; }
mode = ‘GET QUOTED ATTRIBUTE VALUE’;
break;

case ‘COMPLETE’:
parsedValue.content = innerContent;
parsedValue.parsedContent = parseShortCode(innerContent);
break;

}/*endwsitch*/
}/*endwhile*/

if (curAttribute && !parsedValue.attributes[curAttribute]) {
parsedValue.attributes[curAttribute] = ”;
}

s.push(parsedValue);

count++;

//console.log(parsedValue);
}

return s;

}/* END parseShortCode */

});

</script>

 

 

You may also like...