I'm trying to get text from HTML with it's properties (bold, underlined, italic, superscript etc.) but I am struggling with nested ones (like <b> Lorem <u> Ipsum </u></b>, in this case Lorem should be bold and Ipsum should be bold and underlined).
Example Data
<p> Normal<b>Bold</b> <b>Bold<u>Underlined</u></b> <b><i>Bold Italic</i></b><p/>
I need to use this texts in Indesign Script and I need to assign character styles for these properties. Is there any tool or technique for PHP or Javascript that I can use?
Try if DOMParser is available in the environment where you're going to run your JS code.
This parses the html string and outputs a tree structure of the nodes and their texts.
const htmlString = '<p> Normal<b>Bold</b> <b>Bold<u>Underlined</u></b> <b><i>Bold Italic</i></b><p/>';
const htmlElement = (new DOMParser().parseFromString(htmlString, 'text/html')).firstChild.childNodes[1].firstChild;
const tree = convertDomToArray(htmlElement);
console.log(tree);
function convertDomToArray(element) {
if (element.nodeName === '#text') {
return element.nodeValue;
}
let children = [];
for (let childElement of element.childNodes) {
children.push(convertDomToArray(childElement));
}
let output = {};
output[element.nodeName] = children;
return output;
}