Languages
[Edit]
EN

JavaScript - convert string to bytes array

6 points
Created by:
Eshaal-Wilkinson
414

In this short article, we would like to show, how using JavaScriptconvert string to bytes array.

Hint: below solution works under web browser and Node.js JavaScript.

Practical example:

1. to UTF-8 bytes:

// ONLINE-RUNNER:browser;

const toBytes = (text) => {
	const surrogate = encodeURIComponent(text);
  	const result = [];
    for (let i = 0; i < surrogate.length;) {
        const character = surrogate[i];
		i += 1;
        if (character == '%') {
        	const hex = surrogate.substring(i, i += 2);
			if (hex) {
				result.push(parseInt(hex, 16));
			}
        } else {
        	result.push(character.charCodeAt(0));
        }
    }
    return result;
};


// Usage example:

const bytes = toBytes('Some text here...'); // converts string to UTF-8 bytes

console.log(bytes); // [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46]

 

See also

  1. JavaScript - convert bytes array to string

  2. JavaScript - convert string to bytes array under Node.js

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join