首页 > 解决方案 > VueJS如何在字符串中查找特定元素并替换它们

问题描述

如何在 中查找和替换特定html的 -tags vue?我有一些<b><i>-tags 我想用<span>-tags 替换,但我还没有弄清楚如何去做。

例如,我试过这个:

<button @click="replace">Replace</button>

data() {
  return {
    html: 'Lorem ipsum <b>dolor</b> sit amet, consectetur <i>adipiscing</i> elit, sed do eiusmod tempor <b>incididunt</b> ut labore et dolore magna aliqua'
  }
},
methods() {
  replace() {
     this.html.replace('b', '<span style="font-weight:bold">');
     this.html.replace('i', '<span style="font-style:italic">');
  }
}

但这不起作用。

我该如何解决这个问题?

标签: javascriptvue.jsvuejs2

解决方案


原始帖子中的方法存在几个问题。您可能想咨询详细信息String.prototype.replace()

  • replace方法不修改原始字符串;它返回一个新的。所以
this.html = this.html.replace(/*...*/);
  • 您需要替换整个标签,而不仅仅是它的名称。所以
this.html = this.html.replace("<b>", /*...*/);
  • 您还需要替换结束标签。所以
this.html = this.html.replace("<b>", /*...*/).replace("</b>","</span>");
  • 您可能想要替换所有标签,而不仅仅是第一个标签。所以
this.html = this.html.replace(/\<b\>/gi, /*...*/).replace(/\<\/b\>/gi,"</span>");

当然,如果现有元素具有任何属性,这种方法将不起作用


推荐阅读