Vue js 仅对某些 HTML 标签进行转义

发布于 2025-01-14 22:39:27 字数 486 浏览 2 评论 0原文

我正在使用 v-html 来转义 Html 标签,但我只想转义字符串中的 标签。例如

输入:

<p> Hello World </p> <a target="_blank" href="https://www.google.com/">https://www.google.com/</a> <div></div>

输出:链接处于活动状态,但所有其他标签应为纯文本

<p> Hello World </p> https://www.google.com/ <div></div>

如何仅取消转义链接标签并保留Vue 中的其他标签是普通的吗?

I'm using v-html to unescape Html tags But I only want to unescape <a></a> tag in a string. For an example

Input:

<p> Hello World </p> <a target="_blank" href="https://www.google.com/">https://www.google.com/</a> <div></div>

Output: Link is active but all the other tags should be plain text

<p> Hello World </p> https://www.google.com/ <div></div>

How can I unescape only the link tags and leave the other tags plain in Vue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放赐 2025-01-21 22:39:27

这是使用正则表达式将所有 <> 替换为 < 的最简单方法之一和 >,除了 标签周围的内容

new Vue({
  el: "#app",
  data: () => ({
    input: `<p> Hello World </p> <a target="_blank" href="https://www.google.com/">https://www.google.com/</a> <div></div>`
  }),
  computed: {
    output: ({ input }) => input
      .replace(/<(?!\/?a( |>))/g, "<")
      .replace(/(?<=<[^>]+)>/g, ">")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-html="output"></div>
  <pre>output = {{ output }}</pre>
</div>

这两个替换是

  1. 将不属于 的任何 < 替换为 & lt;
  2. 将现在 < 前面的任何 > 替换为 >

请注意,lookbehind 断言不会目前不适用于任何版本野生动物园。

This is one of those times where it's probably just easiest to use a regex to replace all the < and > with < and > except those around <a> tags

new Vue({
  el: "#app",
  data: () => ({
    input: `<p> Hello World </p> <a target="_blank" href="https://www.google.com/">https://www.google.com/</a> <div></div>`
  }),
  computed: {
    output: ({ input }) => input
      .replace(/<(?!\/?a( |>))/g, "<")
      .replace(/(?<=<[^>]+)>/g, ">")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-html="output"></div>
  <pre>output = {{ output }}</pre>
</div>

The two replacements are

  1. Replace any < that is not part of <a> or </a> with <
  2. Replace any > that is now preceded by < with >

Note that lookbehind assertions don't currently work in any version of Safari.

长发绾君心 2025-01-21 22:39:27

HTML 具有可以使用的转义标记:

  • < (<)
  • > (>)

利用这些知识,您可以轻松解决问题。

你好世界

https://www.google.com/

;

=

< p > Hello World < /p > https://www.google.com/ < div > < /div & ;gt;

HTML has escape tags that you can use:

  • < (<)
  • > (>)

Using that knowledge you can easily solve your issue.

<p> Hello World </p> https://www.google.com/ <div></div>

=

< p > Hello World < /p > https://www.google.com/ < div > < /div >

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文