Categories
Vue Answers

How to remove HTML tags from rendered text with Vue.js?

Spread the love

We can remove HTML tags from rendered text in Vue.js using a computed property or a method that utilizes regular expressions to strip the HTML tags.

We can do the following:

Using a Computed Property:

<template>
  <div>
    <p>{{ sanitizedText }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rawText: '<p>This is <b>some</b> <i>HTML</i> <span>text</span>.</p>'
    };
  },
  computed: {
    sanitizedText() {
      return this.rawText.replace(/<[^>]+>/g, '');
    }
  }
};
</script>

In this example, we have a rawText data property containing HTML content.

We use a computed property called sanitizedText to generate a version of rawText with HTML tags removed using a regular expression /<[^>]+>/g.

Using a Method:

<template>
  <div>
    <p>{{ removeTags(rawText) }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rawText: '<p>This is <b>some</b> <i>HTML</i> <span>text</span>.</p>'
    };
  },
  methods: {
    removeTags(text) {
      return text.replace(/<[^>]+>/g, '');
    }
  }
};
</script>

In this example, we define a method called removeTags that accepts a text string as input and returns the same text with HTML tags removed using the same regular expression.

Choose the approach that best fits our use case. Both methods will effectively remove HTML tags from rendered text in Vue.js.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *