简体   繁体   中英

Replace a string to unicode characters

I have a string like blah blah ::e||1f1e6-1f1ea:: blah blah and I want to convert it to blah blah 🇦🇪 blah blah .

🇦🇪 can be written as \\u{1f1e6}\\u{1f1ea} .

I used the code below but it converts to \\u{1f1e6}\\u{1f1ea} this string, not the symbol.

str.replace(/\:\:e\|\|(.*?)\:\:/g, function(x) { return x.replace(/-/g, '\}\\u\{'); }).replace(/\:\:e\|\|(.*?)\:\:/g, "\\u\{$1\}" );

1f1e6 and 1f1ea are the hexadecimal Unicode code points for that character. You can use String.fromCodePoint , but you'll need to use a PolyFill for IE:

text.replace(/::e\|\|([a-f0-9\-]+)::/g, function(match, text) {
    var code_points = text.split('-').map(function(n) {
        return parseInt(n, 16);
    });

    return String.fromCodePoint.apply(undefined, code_points);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM