How can I filter out all other tags other than b, u and i when trying to render content using .innerHTML

Viewed 93

I'm gathering text in form using textarea and I plan to render that text using .innerHTML so that the user can make the content bold, italic and underlined. I might decide to increase the flexibility to allow coloured text using style attribute as well.

I have considered using regex to match the text but I'm hoping for a more elegant solution.

This is what I currently have

      <div class="fullblog-container">
        <textarea name="title" id="fullblogTitle"></textarea>
      </div>
      <button class="addBlock" onclick="submitBlocks()">SUBMIT</button>
       const fullBlogContainer = document.querySelector(".fullblog-container");
      function submitBlocks() {
        const allChildren = Array.from(fullBlogContainer.children);
        const filterChildren = allChildren.filter((elem) => elem.tagName != "BUTTON");
        console.log(filterChildren[0].value);
      }

The above code gets the output from (currently only 1 textarea) all my textareas.

I plan to rendder that value using .innerHTML and wish to retain b, u, i tags and maybe div tags with style attributes, and treat the rest as text.

Edit: Although my question results in preventing injection attacks (similar question exists) I require a way to render certain parts as text and other parts as html, and I haven't found a suitable solution for this.

PS: NO JQuery please

1 Answers

One approach is to convert all elements to text and whitelist elements you want to allow. With innerText the browser converts all html entities to their code. Then you can read actual code with innerHTML and replace whitelisted elements.

const dangerousContent = '\<script\>dangerousFunction()\</script\>';
const content = 'Text \<b\>bold\</b\> \<i\>italic\</i\>  \<u\>underline\</u\>';

const container = document.getElementById('container');

container.innerText += dangerousContent;
container.innerText += content;
container.innerHTML = container.innerHTML
                               .replace(/&lt;b&gt;/g, '\<b\>')
                               .replace(/&lt;\/b&gt;/g, '\</b\>')
                               .replace(/&lt;i&gt;/g, '\<i\>')
                               .replace(/&lt;\/i&gt;/g, '\</i\>')
                               .replace(/&lt;u&gt;/g, '\<u\>')
                               .replace(/&lt;\/u&gt;/g, '\</u\>');
<span id="container"></span>

Related