【问题标题】:Show tooltip text in a string with custom tags在带有自定义标签的字符串中显示工具提示文本
【发布时间】:2022-01-04 09:41:30
【问题描述】:

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

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="">$2</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.

【问题讨论】:

  • 是的,这是输出。

标签: javascript regex string replace


【解决方案1】:

你可以使用

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] 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多