Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript unicode to ASCII

Need to convert the unicode of the SOH value '\u0001' to Ascii. Why is this not working?

var soh = String.fromCharCode(01);
It returns '\u0001'
Or when I try

var soh = '\u0001' It returns a smiley face.
How can I get the unicode to become the proper SOH value(a blank unprintable character)

like image 650
Newbie_Techie Avatar asked Jan 28 '26 15:01

Newbie_Techie


1 Answers

JS has no ASCII strings, they're intrinsically UTF-16.

In a browser you're out of luck. If you're coding for node.js you're lucky!

You can use a buffer to transcode strings into octets and then manipulate the binary data at will. But you won't get necessarily a valid string back out of the buffer once you've messed with it.

Either way you'll have to read more about it here:

https://mathiasbynens.be/notes/javascript-encoding

or here:

https://nodejs.org/api/buffer.html


EDIT: in the comment you say you use node.js, so this is an excerpt from the second link above.

const buf5 = Buffer.from('test');
// Creates a Buffer containing ASCII bytes [74, 65, 73, 74].

To create the SOH character embedded in a common ASCII string use the common escape sequence\x01 like so:

const bufferWithSOH = Buffer.from("string with \x01 SOH", "ascii");

This should do it. You can then send the bufferWithSOH content to an output stream such as a network, console or file stream.

Node.js documentation will guide you on how to use strings in a Buffer pretty well, just look up the second link above.

like image 119
pid Avatar answered Jan 31 '26 04:01

pid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!