Naim Berk Tumer
Naim Berk Tumer

Reputation: 129

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\}" );

Upvotes: 1

Views: 125

Answers (1)

Blender
Blender

Reputation: 298076

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

Upvotes: 4

Related Questions