javascript - 使用正则表达式删除带有内联 css 的 B 标记
问题描述
我有这样的内容。
<strong>Citation1:</strong> Firs<b style="font-weight:bold">t</b> Ci<b style="font-weight:bold">t</b>a<b style="font-weight:bold">t</b>ion
我想<b>
使用下面使用的正则表达式删除所有标签,但它不适用于多个 b 标签。
function removeBoldString(str) {
const re = new RegExp('(<b(.*)">)|(</b>)', 'g');
return str.replace(re, '');
}
解决方案
你需要使用类似的东西,[^>]*
而不是.*
,这里是一个例子:
const str = `<strong>Citation1:</strong> Firs<b style="font-weight:bold">t</b> Ci<b style="font-weight:bold">t</b>a<b style="font-weight:bold">t</b>ion`;
function removeBoldString(str) {
const re = new RegExp('(<b([^>]*)">)|(</b>)', 'g');
return str.replace(re, '');
}
const result = removeBoldString(str);
console.log(result);
但是使用正则表达式处理 HTML 并不是一个好主意,在 JavaScript 中有很多处理 HTML 的方法,特别是如果您在浏览器中执行此操作。这是一个例子:
const str = `<strong>Citation1:</strong> Firs<b style="font-weight:bold">t</b> Ci<b style="font-weight:bold">t</b>a<b style="font-weight:bold">t</b>ion`;
const doc = new DOMParser().parseFromString(str, 'text/html');
doc.querySelectorAll('b').forEach((b) => {
b.replaceWith(doc.createTextNode(b.textContent));
});
console.log(doc.body.innerHTML);
推荐阅读
- queue - ActiveMQ 代理从消费者那里获得持续的空消息拉取尝试
- swagger - 是否可以在 Swagger 中添加自定义页面?
- python - 读取目录中的多个 Excel 文件并附加到 Pandas 数据框
- c++ - MFC MDI 向文档添加第二个视图
- webpack - Webpack 输出只创建 dist 文件夹而不是 dist.zip
- javascript - 使用箭头键导航下拉结果,同时保持对文本框的关注
- spring-boot - spring kafka - 交易问题
- css - 在 Sass 文件中编写 CSS 会在 Angular 7 中引发错误
- visual-studio-code - VSCode programmatically find latest extension version on marketplace
- java - How to block a ListPreference dialog from opening when that ListPreference was clicked on?