我有一个带有自定义标记的字符串,并尝试获取工具提示的文本并将其添加到<span>属性标题中。我将自定义的[message]标记替换为<span>,但是如何通过代码获取text属性。我尝试了一些match和includes的选择,但也许我错了。如果有人能帮我,我会非常感激的。Т汉克斯。
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.发布于 2021-11-26 10:16:12
您可以使用
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 text[^\]]* -除]\scode="以外的零或多个字符-单个空格和code=" text([^"]*) -第1组(code正在替换):除""[^\]]*] - "以外的任何零或多个字符,除char([\w\W]*?)以外的任何零或多个字符,然后是] ] - Group 2(替换中的text变量):任何与possible\[\/message]一样少的零或多个字符-- [/message]字符串.https://stackoverflow.com/questions/70122526
复制相似问题