Skip to content
Advertisement

How to replace Unicode characters in the following scenario using javascript?

How to replace Unicode characters in the following scenario using javascript? Using javascript I want to replace Unicode characters with a wrapper according to their style. If possible include a range of Unicode characters([a-z]) in regex for styles other than regular.

  • input = abc𝑢𝑣𝑤𝑥𝐚𝐛𝐜𝐝𝒇𝒈𝒉𝒊
  • expected ouput = <span class="regular>abc</span><i> 𝑢𝑣𝑤𝑥</i><b>𝐚𝐛𝐜𝐝</b><b><i>𝒇𝒈𝒉𝒊</i></b>

text = 'abc𝑢𝑣𝑤𝑥𝐚𝐛𝐜𝐝𝒇𝒈𝒉𝒊';
text = text.replace(/([a-z]+)/,'<span class="regular">$1</span>');
text = text.replace(/([𝑎𝑏𝑐𝑑𝑒𝑓𝑔ℎ𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧]+)/,'<i>$1</i>');
text = text.replace(/([𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳]+)/,'<b>$1</b>');
text = text.replace(/([𝒂𝒃𝒄𝒅𝒆𝒇𝒈𝒉𝒊𝒋𝒌𝒍𝒎𝒏𝒐𝒑𝒒𝒓𝒔𝒕𝒖𝒗𝒘𝒙𝒚𝒛]+)/,'<b><i>$1</i></b>');

Advertisement

Answer

I think it’s just a matter of finding the Unicode ranges you want to replace, and normalizing (decomposing) the string:

let text = 'abc𝑢𝑣𝑤𝑥𝐚𝐛𝐜𝐝𝒇𝒈𝒉𝒊';
text = text.replace(/[u{1d41a}-u{1d433}]+/gu, s => `<b>${s.normalize('NFKD')}</b>`);
text = text.replace(/[u{1d44e}-u{1d467}]+/gu, s => `<i>${s.normalize('NFKD')}</i>`);
text = text.replace(/[u{1d482}-u{1d49b}]+/gu, s => `<b><i>${s.normalize('NFKD')}</i></b>`);

console.log(text);
Advertisement