You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取自定义标签中tooltip文本并写入span的title属性

实现方案

你可以先把提供的配置数组转成code到text的映射表,再利用String.prototype.replace的回调函数功能,匹配到标签后提取code值,查询对应文本再拼接成目标span标签即可。你之前只用到了replace的静态字符串替换功能,没法动态根据匹配到的内容调整替换值,用回调函数就可以实现动态处理每一个匹配结果的需求。

完整实现代码如下:

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

// 构建code到提示文本的映射,提升查询效率
const codeToText = new Map(obj.map(item => [item.code, item.text]));

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, (match, openTag, content) => {
  // 从起始标签中提取code属性值
  const codeMatch = openTag.match(/code="([^&]+)"/);
  const tipText = codeMatch ? codeToText.get(codeMatch[1]) || '' : '';
  // 拼接返回带正确title属性的span标签
  return `<span class="tooltip" title="${tipText}">${content}</span>`;
});

运行后updateStr的值就和你给出的预期输出完全一致。


内容的提问来源于stack exchange,提问作者alexanderstanchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:36:07