在带有自定义标签的字符串中显示工具提示文本

Show tooltip text in a string with custom tags

我有一个带有自定义标签的字符串,并尝试获取 工具提示 的文本并将其添加到 <span> 属性 标题。我用 <span> 替换了自定义 [message] 标签,但是如何通过 code 获取 text 属性。我用 matchincludes 尝试了一些选项,但也许我错了。如果有人可以帮助我,我将不胜感激。谢谢。

let obj = [
  {
    code: 'MESSAGE_1',
    text: 'Basic tooltip text',
    type: 'TOOLTIP'
  },
  {
    code: 'MESSAGE_2',
    text: 'Again, basic tooltip text',
    type: 'TOOLTIP'
  },
];

let str = 'A really ironic artisan [message type="TOOLTIP" code="MESSAGE_1"]whatever keytar[/message], scenester farm-to-table banksy Austin twitter handle freegan cred raw denim [message type="TOOLTIP" code="MESSAGE_2"]single-origin[/message] coffee viral.'

let updateStr = str.replace(/(\[message[^\]]*\])(.+?)(\[\/message\])/g, '<span class="tooltip" title=""></span>');

预期输出:

A really ironic artisan <span class="tooltip" title="Basic tooltip text">whatever keytar</span>, scenester farm-to-table banksy Austin twitter handle freegan cred raw denim <span class="tooltip" title="Again, basic tooltip text">single-origin</span> coffee viral.

你可以使用

let obj = [
  {
    code: 'MESSAGE_1',
    text: 'Basic tooltip text',
    type: 'TOOLTIP'
  },
  {
    code: 'MESSAGE_2',
    text: 'Again, basic tooltip text',
    type: 'TOOLTIP'
  },
];

let str = 'A really ironic artisan [message type="TOOLTIP" code="MESSAGE_1"]whatever keytar[/message], scenester farm-to-table banksy Austin twitter handle freegan cred raw denim [message type="TOOLTIP" code="MESSAGE_2"]single-origin[/message] coffee viral.'

let updateStr = str.replace(/\[message[^\]]*\scode="([^"]*)"[^\]]*]([\w\W]*?)\[\/message]/g, (_,code,text) => `<span class="tooltip" title="${obj.find(x=> x.code == code).text}">${text}</span>`);
console.log(updateStr);

\[message[^\]]*\scode="([^"]*)"[^\]]*]([\w\W]*?)\[\/message] 正则表达式匹配

  • \[message - [message 文字
  • [^\]]* - ]
  • 以外的零个或多个字符
  • \scode=" - 一个空格和 code=" 文本
  • ([^"]*) - 第 1 组(code 替换):除 "
  • 之外的任何零个或多个字符
  • "[^\]]*] - ",除 ] 之外的任何零个或多个字符,然后是 ] 字符
  • ([\w\W]*?) - 第 2 组(text 替换变量):尽可能少的任何零个或多个字符
  • \[\/message] - [/message] 字符串。