1

An API I'm using is sending a message that contains an escaped Unicode character like below and can't get this to print out to the screen correctly.

message: "\ud83d\udc4d hello"

I've tried using the innerHTML method, but it just prints everything as a string.

<div class="comment-content" [innerHTML]="c.message"></div> 

Is there a way to unescape this so it can be displayed in the view correctly?

edit I've created a pipe for this and tried encoding/ escaping it along with bypassing Security with DomSanitizer.

 import { Pipe, PipeTransform } from '@angular/core';
 import {DomSanitizer} from '@angular/platform-browser';

@Pipe({
  name: 'safeHTml'
})
export class UnicodePipe implements PipeTransform {    
  constructor(private sanitized: DomSanitizer) {
  }
  transform(value: any, args?: any): any {
    return  this.sanitized.bypassSecurityTrustHtml(unescape(encodeURIComponent(value));
  }
}
bstory
  • 852
  • 9
  • 28
  • You will need to map the API response in your service and use javascript to decode unicode, have a look at this: https://stackoverflow.com/questions/10576905/how-to-convert-javascript-unicode-notation-code-to-utf-8 – Mehdi Benmoha Dec 30 '19 at 16:20
  • Sweet this is closer than I've been able to get, I could probably create an angular pipe for this yeah? – bstory Dec 30 '19 at 16:26
  • I attempted this and it didn't print out the thumbs up icon. I'm still stumped. :( – bstory Dec 30 '19 at 16:43
  • Oh sorry, you're trying to print emojis, there are special HTML codes for them, you can grab them from here: https://www.w3schools.com/charsets/ref_emoji.asp – Mehdi Benmoha Dec 30 '19 at 17:06
  • I'm trying to take what I get back from the API and render it inside of the view, so far I've not been able to. I dont know of a way to use those html codes for emojis. Unicode should work but it's being printed as a string. – bstory Dec 30 '19 at 18:33
  • Yes, it should work straight forward, I can't reproduce your bug, here's a simple example https://stackblitz.com/edit/angular-yp3kpy – Mehdi Benmoha Dec 30 '19 at 19:11

1 Answers1

0

The solution is a mix of these ideas, ultimately here is the code in my pipe that transforms the string and allows Unicode to be read.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'unicode'
})
export class UnicodePipe implements PipeTransform {
  constructor() {
  }
  transform(value: any, args?: any): any {
    return decodeURIComponent(JSON.parse('"' + value.replace(/\"/g, '\\"') + '"'));
  }
}
bstory
  • 852
  • 9
  • 28