1

In vuejs, is it possible to wrap certain parts of the text inside HTML tags?

Like Hello %John%. How are you doing? to become Hello <b>%John%</b>. How are you doing?

with a filter like

{{text | wrapText}}
2
  • Did you have a a look at v1.vuejs.org/guide/custom-filter.html ? Commented Oct 24, 2019 at 12:39
  • yes but there is no mention of html Commented Oct 24, 2019 at 12:40

3 Answers 3

1

You can write your own filter. See this fiddle

Vue.filter('wrapText', function (text) {
  let a = text.split('%');
  let str = '';
  for (let x = 0; x < a.length; x++) {
    str += a[x];
    if (x % 2 == 0) {
        if (x < a.length - 1)
        str += '<b>';
    }
    else {
        str += '</b>';
    }
  }
  return str
});
Sign up to request clarification or add additional context in comments.

Comments

0

I never worked with vue but I read a little bit in the last 15 mins and i guess i found a solution.

You can play around with the javaScript method.There might be a cleaner way to achieve the same result.

The important fact is to use the vue custom filters with :inner-html.prop. It doesn't look very 'safe' but if you control what html gets inserted there you should be ok.

So in html you can do something like <span :inner-html.prop="text | wrapText"></span>

And then declare your filter. I read there are two ways to declare them: globally or inside the component, you choose.

Globally

Vue.filter('wrapText', function (value) {
  const wordToWrap = value.substring(
    value.indexOf("%")+1, 
    value.lastIndexOf("%")
  )

  const wrappedWord = `<b>${wordToWrap}</b>`

  value = value.replace(wordToWrap, wrappedWord)

  return value;
})

And this should work. I got it to work on a vue playground. Cheers !

Comments

0

Regex is the way :D

Edit: "2.0 filters only work in mustache tags and v-bind."

cfr: https://github.com/vuejs/vue/issues/4352

new Vue({
  el: "#app",
  data: {
    text: 'Hello %John%. How are you doing %today%?'
  },
  filters: {
    wrapText(str) {
      return this.wrapText(str)
    }
  },
  methods: {
      wrapText(str) {
    	if (str.includes('%')) {
          const reg = /(%[A-Za-z0-9]*%)/g
          const newStr = str.replace(reg, '<b>$1</b>')
          return newStr
        }
        return str
    }
  }
})
<div id="app">
  <h2>This is a text</h2>
  <p v-html="wrapText(text)">
  </p>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

The filter part is no longer needed but I've left it anyway.

2 Comments

good idea with the regex. The problem was not the filter but how to insert HTML. <b>%John%</b> doesn't look html to me :)
I forgot the last part, sorry. I am going to fix it. Fixed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.