首页 > 解决方案 > 使用正则表达式删除带有内联 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, '');
}

标签: javascriptregex

解决方案


你需要使用类似的东西,[^>]*而不是.*,这里是一个例子:

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


推荐阅读