Escape text in a method instead of in brackets in Vue

629 Views Asked by At

I've got a case where I have a text that begins with characters like   that I do not want to escape, but then the rest of the string I do want to escape.

In Vue, given text = "&nbsp;&nbsp;<strong>something</strong>", if I do:

<p>{{ text }}</p>

It escapes all text, including the &nbsp;, printing out:

&nbsp;&nbsp;<strong>something</strong>

If I do this:

<p v-html="text"></p>

Then I get:

  something

What I want to achieve is not escaping the &nbsp; but escaping all the rest of the html. My thought was doing something like this:

<p v-html="formatText()"></p>
<script>
methods: {
  formatText() {
    return '&nbsp;&nbsp;' + e('<strong>something</strong>');
  }
}
</script>

where e would be some function that escapes the undesired html.

Does Vue have a method like that? Or is that something I'd have to write up? I'm not sure how Vue does its escaping under the hood.

2

There are 2 best solutions below

0
Chris On

So I haven't found an answer yet to if Vue has a way to do this natively. But for the meantime I've done the following:

<p v-for="line in messageLines">
  <span v-html="extractIndent(line)"></span>{{ line.trim() }}
</p>

<script>
methods: {
  extractIndent(line) {
    let indent = '';
    for (let i = 0; i < line.length; i++) {
      if (line.charAt(i) === ' ') {
        indent += '&nbsp;';
      } else {
        break;
      }
    }
    return indent;
  }
}
</script>

This takes a text like " An indented text" and turns the spaces into &nbsp; and puts them in the <span> unescaped, and then escapes all the rest of the text by using Vue's brackets.

Good enough for what I need for now.

0
Rohìt Jíndal On

You can achieve this by using RegEx with the help of String.replace() method.

Live Demo :

new Vue({
  el: '#app',
  data: {
    text: '&nbsp;&nbsp;<strong>something</strong>'
  },
  mounted() {
    this.text = this.text.replace(/[^&nbsp;].*/, '');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p>{{ text }}</p>
</div>