0

I am using node-fetch to read data from URL. The return result is perfect except it is different from my preferred result. For some special characters like í or this ř, I want it instead to be in the format as following: u00ed and u0159. Is it possible to achieve something like that without looking up for the character and replacing it manually?

Here is my code:

const fetch = require("node-fetch");
var result = {}
fetch(url)
.then(res => res.json())
.then(json => result = json);

My json result:

{"title":"Adopce zvířat"}

In stead of the result above, I want:

{"title":"Adopce zv\\u00ed\\u0159at"}

It must be strange but for some reason I want it that way.

Jane
  • 151
  • 3
  • 12
  • Welcome to Stackoverflow Jane! Could you add the code you are using by editing your question so that we can help you better? – wuerfelfreak Apr 11 '21 at 09:45

2 Answers2

1

You could use the jsesc package:

const jsesc = require('jsesc');

jsesc('Ich ♥ Bücher'); // → 'Ich \\u2665 B\\xFCcher'

jsesc('foo  bar'); // → 'foo \\uD834\\uDF06 bar' 

From the Documentation on Github

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
0

This funktion from GitHub Gist User josephrocca found here on GitHub Gist replaces all non-ASCII characters with there unicode escape string.

function escapeUnicode(str) {
  return [...str].map(c => /^[\x00-\x7F]$/.test(c) ? c : c.split("").map(a => "\\u" + a.charCodeAt().toString(16).padStart(4, "0")).join("")).join("");
}

This function matches all non-ASCII characters after splitting the string in a "unicode-safe" way (using `[...str]`). It then splits each unicode character up into its code-points, and gets the escape code for each, and then joins all all the ASCII characters and Unicode escapes into one string.

[...]

Based on discussion in this thread: https://gist.github.com/mathiasbynens/1243213

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29