使用正则表达式使用内联 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);

最新更新