How to remove HTML tags from rendered text

Zach Tackett picture Zach Tackett · Jun 5, 2017 · Viewed 18k times · Source

I am needing to remove the opening and closing <p> tags from some rendered comment text. I pass the content to a component as a prop and i think that in doing so, it doesn't allow for the v-html directive to work correctly.

I need the content to render without the html tags

Here is where I am trying to render normally with v-html

 <textarea class="form-control comment-inline-edit" v-html="content" name="comment-inline-edit" cols="45" rows="3"></textarea>

And here is where I am passing the rendered content from the parent component

<CommentEdit v-show="isEditting" :content="comment.content.rendered" v-on:cancel="cancelEdit" />

Is there a VueJS way to do this other than using v-html?

Answer

Grant picture Grant · Nov 8, 2017

I would recommend you strip HTML from rendered text in VueJS using a filter, that way you can repeatedly use the filter around the application, rather than a specific singular computation.

I wrote the following, which utilises the browser's parsing (most reliable method) as regex can be thwarted by user silliness:

Vue.filter('striphtml', function (value) {
  var div = document.createElement("div");
  div.innerHTML = value;
  var text = div.textContent || div.innerText || "";
  return text;
});

Once you include this in your app.js you can then render it anywhere as follows:

{{ pdf.description | striphtml }}