Javascript VueJS如何在字符串中查找特定元素并替换它们

Javascript VueJS如何在字符串中查找特定元素并替换它们,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,如何在vue中查找和替换特定的html-标记?我有一些和-标记,我想用-标记替换它们,但我还没有弄清楚怎么做 例如,我尝试了以下方法: <button @click="replace">Replace</button> data() { return { html: 'Lorem ipsum <b>dolor</b> sit amet, consectetur <i>adipiscing</i> elit, s

如何在
vue
中查找和替换特定的
html
-标记?我有一些
-标记,我想用
-标记替换它们,但我还没有弄清楚怎么做

例如,我尝试了以下方法:

<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">');
  }
}
替换
数据(){
返回{
html:“Lorem ipsum door sit amet,奉献精英,sed do eiusmod temporal incident ut laboure et dolore magna aliqua”
}
},
方法(){
替换(){
this.html.replace('b','');
this.html.replace('i','');
}
}
但这是行不通的


我该如何解决这个问题呢?

原始帖子中的方法有几个问题。您可能需要查阅详细信息以了解更多信息

  • replace
    方法不修改原始字符串;它返回一个新的。所以
  • 您需要替换整个标记,而不仅仅是它的名称。所以
this.html=this.html.replace(“,/*…*/);
  • 您还需要替换结束标记。所以
this.html=this.html.replace(“,/*…*/).replace(“,”);
  • 您可能希望替换所有标记,而不仅仅是第一个标记。所以
this.html=this.html.replace(/\/gi,/*…*/).replace(/\/gi,“”);
当然,如果现有元素有任何属性,这种方法将不起作用

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>");