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);