javascript - 将多次出现的 && 替换为 <b>,将 %% 替换为 <i> 标记

标签 javascript regex html-parsing regex-group

我正在开发一个自定义解析函数,我需要用它来解析字符串 && 与 <b> 多次重复出现和 %% 与 <i>标签。

我尝试了这个正则表达式。

html = html.replace(/[&][&](.+?)[&][&]/g, '<b>$1</b>');
html = html.replace(/[%][%](.+?)[%][%]/g, '<i>$1</i>');

上面的替换对于我的意思是单个组来说效果很好

“&&This&& is a &&bold string&&”到“this is a bold string

这给出了奇怪的结果,我有重复的字符串

&&&&This&&&& is a &&bold string&& 

<b>&&This</b>&& is a <b>bold String</b>

需要帮助解析结束组和开始组,以将其替换为正确的 html 标签,例如

<b><b>This</b></b> is a <b>bold String</b>

如果可能的话,仅用一个 <b> 替换它标签

<b>This</b> is a <b>bold String</b>

最佳答案

一种选择是匹配尽可能多的 &尽可能连续,至少需要两个:

console.log(
  '&&&&This&&&& is a &&bold string&&'
    .replace(/&{2,}(.*?)&{2,}/g, '<b>$1</b>')
);

请注意,如果您想同时替换 &<b>标签和 %<i>标签,您可以使用单个正则表达式和访问对象的替换函数:

const obj = {
  '&': 'b',
  '%': 'i'
};
console.log(
  '&&&&This&&&& is a &&bold string&& and there are italics %%here%%%'
    .replace(
      /([%&])\1+(.*?)\1{2,}/g,
      (_, char, text) => `<${obj[char]}>${text}</${obj[char]}>`
    )
);

如果您希望要求两端的组平衡,那么不仅要捕获组中的一个字符,还要捕获 & 的整个子字符串。或% s,这样您就可以稍后反向引用整个子字符串:

const obj = {
  '&': 'b',
  '%': 'i'
};
console.log(
  '&&&&This&& is a &&bold string&& and there are italics %%here%%%'
    .replace(
      /(([%&])\2+)(.+?)\1/g,
      (_, _2, char, text) => `<${obj[char]}>${text}</${obj[char]}>`
    )
);

如果部分没有整齐地嵌套在其他部分中(例如 <b>foo<i>bar</b>baz</i> ),那么您必须使用原始方法来替换 && s,然后再次遍历字符串并替换 %% s:

console.log(
  '&&&&This&& is a &&bold string&& and there are italics %%here%%%'
    .replace(/(&{2,})(.+?)\1/g, '<b>$2</b>')
    .replace(/(%{2,})(.+?)\1/g, '<i>$2</i>')
);

关于javascript - 将多次出现的 && 替换为 <b>,将 %% 替换为 <i> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293072/

相关文章:

javascript - 使用 mootools 列表到 GridView

javascript - 日期正则表达式

ruby - 使用 Nokogiri 获取 HTML 结构

javascript - 选择接下来的 2 位以 XXX 开头但不是 XXX 的数字

C# 正则表达式 : match a string starting with x and ending with y, 不包括结尾部分 & 匹配模式的最后一次出现

php DOMDocument nodeName 属性返回 '#text' 和 nodeName

python - 如何在 lxml iterwalk 循环中用文本替换 HTML 标签

javascript - 使用嵌套的 ngFor 遍历两个单独的数组

JavaScript:在其他函数中评估函数

javascript - 嵌套DIV表(即表中表),如何用所有数据构建一个对象?