Home > Mobile >  Escape text in a method instead of in brackets in Vue
Escape text in a method instead of in brackets in Vue

Time:10-24

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>

methods: {
  formatText() {
    return '&nbsp;&nbsp;'   e('<strong>something</strong>');
  }
}

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.

CodePudding user response:

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>

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

      return indent;
    }
  }

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.

CodePudding user response:

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>

  • Related