javascript - 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">');
}
}
但这不起作用。
我该如何解决这个问题?
解决方案
原始帖子中的方法存在几个问题。您可能想咨询详细信息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>");
当然,如果现有元素具有任何属性,这种方法将不起作用
推荐阅读
- .htaccess - 如何在 Laravel 中为 ads.txt 进行重定向
- r - 在代码中使用 Markdown 闪亮参数,而不仅仅是在图形生成中
- markdown - 使用 Jekyll 生成“参数”页面
- python - skimage.util 中错误的像素值缩放(替代 Scipy 中的字节缩放)
- amazon-web-services - AWS EB Flask 应用程序部署无法获得 HTTP 标头授权
- c - 如何使用 OpenMP 减少循环中 FFT 的执行时间?
- spring - 对 .NET Core REST api 的大型 POST 请求的 Spring RestTemplate 404 错误
- sql - 这个查询有什么问题?双引号错误
- c# - 我在行走和跑步动画之间切换的脚本不起作用
- java - 以降序交替排序2个整数数组列表