1

I am using an API to compile code, and when there is an error, the response containing the error message uses JSON escape characters, but when outputting it back into the HTML front-end, it just produces garbage characters. How can I either convert the escaped string to a plain text string using Javascript, or output it in HTML correctly?

This is what the string looks like properly outputted (in Powershell):

https://i.stack.imgur.com/9tDQG.jpg

This is the escaped string:

\u001b[01m\u001b[K:\u001b[m\u001b[K In function '\u001b[01m\u001b[Kin...

This is what the string looks like if I directly output it in HTML:

[01m[K:[m[K In function '[01m[Kint main()[m[K': [01m[K:9:1:[m[K [01;31m[Kerror: [m[Kexpected '[01m[K;[m[K' before '[01m[K}[m[K' token } [01;32m[K ^[m[K

2 Answers2

2

Looks like you can use the strip-ansi package. Here's an example using your escaped string:

const stripAnsi = require('strip-ansi');

stripAnsi("\u001b[01m\u001b[K:\u001b[m\u001b[K In function '\u001b[01m\u001b[Kin...")

// result => ": In function 'in..."

If you aren't using node.js, or cannot use that package for whatever reason, this Stack Overflow answer has a regular expression you may be able to use instead.

Michael Oliver
  • 1,392
  • 8
  • 22
1

Just found this tool too:

https://www.npmjs.com/package/ansi-to-html

which converts ANSI to html.