JavaScript string to byte array | Convert to Example code

  • by

How to convert a string in byteArray using JavaScript?

JavaScript Strings are stored in UTF-16. To get UTF-8, you’ll have to convert the String yourself.

JavaScript string to byte array example

HTML example code.


		var str = "Hello";
		var bytes = []; 
		var bytesv2 = []; 

		for (var i = 0; i < str.length; ++i) {
			var code = str.charCodeAt(i);

			bytes = bytes.concat([code]);

			bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);

		console.log('bytes', bytes.join(', '));

		console.log('bytesv2', bytesv2.join(', '));



convert JavaScript string to byte array

Do comment if you have any doubts and suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.