Vuejs Convert HTML to Plain text

Viewed 6311

I want to convert HTML to plain text using vuejs.

<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>

I used v-html but this parse HTML sting to HTML like below

 1. The quick brown fox jumps over the lazy dog
 2. The quick brown fox jumps over the lazy dog 
 3. The quick brown fox jumps over the lazy dog
 4. The quick brown fox jumps over the lazy dog

But I want result to be like this.

The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog

I could do this with angularjs or javascript but I couldn't found anything with vuejs

Note: I'm not using jquery in my project.

2 Answers

what about custom directives

Vue.directive('plaintext', {
  bind(el, binding, vnode) {
    el.innerHTML = el.innerText;
    //el.innerHTML = el.innerHTML.replace(/<[^>]+>/gm, '');
  }
});

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">

  <ol v-plaintext>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
  </ol>
</div>

try to convert from css

var vm = new Vue({
  el: '#vue-instance',
  data: {
    html: `<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>` 
  }
});
ol{
  list-style: none;
}
ol li{
  display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
  <div v-html="html"></div>
</div>

Another way using hidden div

var vm = new Vue({
  el: '#vue-instance',
  computed:{
    newHTML: function(){
      document.querySelector("#temp").innerHTML = this.html;
      var textContent = document.querySelector("#temp").textContent;
      document.querySelector("#temp").innerHTML = "";
      return textContent;
    }
  },
  data: {
    html: `<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>`
  }
});
.hide{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
  <div>{{newHTML}}</div>
</div>
<div class="hide" id='temp'>123</div>

Related