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}}
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}}
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
});
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 !
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.