I have a string with custom tags and try to get the text for the tooltip and add it in the <span> propery title. I replaced the custom [message] tag with <span> but how to get the text property by code. I tried some options with match and includes but maybe I'm wrong. If anyone can help me I will be very grateful. Т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>');
Expected output:
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.
You can use
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);
The \[message[^\]]*\scode="([^"]*)"[^\]]*]([\w\W]*?)\[\/message] regex matches
\[message - [message text[^\]]* - zero or more chars other than ]\scode=" - a single whitespace and code=" text([^"]*) - Group 1 (code in replacement): any zero or more chars other than ""[^\]]*] - ", any zero or more chars other than ] and then a ] char([\w\W]*?) - Group 2 (text variable in replacement): any zero or more chars as few as possible\[\/message] - a [/message] string.