0

I have this XML string which I am displaying as a text in a document:

<p>The new strain of <s alias="coronavirus">COVID</s>seems to be having a greater spread rate.</p>

The following function returns the text form of the XML:

function stripHtml(html) {
  // Create a new div element
  var temporalDivElement = document.createElement("div");
  // Set the HTML content with the providen
  temporalDivElement.innerHTML = html;
  // Retrieve the text property of the element (cross-browser support)
  return temporalDivElement.textContent || temporalDivElement.innerText || "";
}

The problem is, this function returns the following string:

The new strain of COVIDseems to be having a greater spread rate.

which is nearly what I want, but there is no space between the word COVID and seems. Is it possible that I can add a space between contents of two tags if it doesn't exist?

1 Answer 1

2

One option is to iterate over text nodes and insert spaces at the beginning if they don't exist, something like:

const getTextNodes = (parent) => {
    var walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT, 
        null, 
        false
    );

    var node;
    var textNodes = [];

    while(node = walker.nextNode()) {
        textNodes.push(node);
    }
    return textNodes;
}


function stripHtml(html) {
  // Create a new div element
  var temporalDivElement = document.createElement("div");
  // Set the HTML content with the providen
  temporalDivElement.innerHTML = html;
  // Retrieve the text property of the element (cross-browser support)
  for (const node of getTextNodes(temporalDivElement)) {
    node.nodeValue = node.nodeValue.replace(/^(?!\s)/, ' ');
  }
  return temporalDivElement.textContent.replace(/  +/g, ' ').trim();
}

console.log(stripHtml(`<p>The new strain of <s alias="coronavirus">COVID</s>seems to be having a greater spread rate.</p>`));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.