显示字符串为HTML
如何渲染一个字符串以HTML的形式显示? 我试图接受各种字符串。我应该能够检查字符串是否为HTML,如果是,我需要使用HTML格式显示它,否则正常显示为字符串。
示例:
<template>
<div v-for="msg in msgs" :key="msg">
{{ msg }}
</div>
</template>
// msgs will look like this:
const msgs = ['hello there', '<b>print this in bold</b>', '<br/>', 'and this is in another line']
我试图做类似的事情:
<template>
<div v-for="msg in msgs" :key="msg">
{{ isHtml(msg) ? processAsHtml(msg) : msg }}
</div>
</template>
其中processAshtml
是这样的:
const parser = new DOMParser()
function processAsHtml (htmlString) {
return parser.parseFromString(htmlString, 'text/html')
}
但是,这将HTML线打印为“ [对象htmldocument]”的
帮助!
谢谢!
How can I render a string to be displayed as an html?
I am trying to accept an array of strings. I should be able to check if the string is an html, if yes, I need to display it with html formatting, otherwise display normally as a string.
Example:
<template>
<div v-for="msg in msgs" :key="msg">
{{ msg }}
</div>
</template>
// msgs will look like this:
const msgs = ['hello there', '<b>print this in bold</b>', '<br/>', 'and this is in another line']
I tried to do something like this:
<template>
<div v-for="msg in msgs" :key="msg">
{{ isHtml(msg) ? processAsHtml(msg) : msg }}
</div>
</template>
Where processAsHtml
is like this:
const parser = new DOMParser()
function processAsHtml (htmlString) {
return parser.parseFromString(htmlString, 'text/html')
}
But this prints the html lines as "[object HTMLDocument]"
Help!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用V-HTML
you can use v-html
如其他建议,仅在模板中打印行HTML,您可以直接使用
v-html
指令。但是,如果您想检查哪些字符串是正常的字符串,哪些是正常的字符串。您可以在Regex和
string.match()
方法。实时演示:
注意: as
建议在这种情况下请检查XSS漏洞。最佳实践是在HTML结合之前对弦进行消毒。Nikola
As other suggested, Just to print the row HTML in the template you can directly use
v-html
directive.But If you want to check that which strings are normal strings and which are not a normal. That you can check with the help of regex and
String.match()
method.Live Demo :
Note : As
Nikola
suggested, Kindly check for the XSS Vulnerabilities in this case. Best practice is to sanitize the strings which is not normal before binding in HTML.