To convert a string to char code in JavaScript, you can use the “charCodeAt()” method.
The charCodeAt() method takes an index of characters from the string we want to convert into Unicode.
Syntax
string.charCodeAt(index);
Parameters
Index – It is an index number of our string. By default, it is 0.
Return type
Number: It will return a Unicode of our character. If our index is not valid, then it will return NaN.
Example
const string = "Wonderful People";
console.log(string.charCodeAt(0));
console.log(string.charCodeAt(5));
console.log(string.charCodeAt(8));
console.log(string.charCodeAt(32));
Output
87
114
108
NaN
In the above example, we pass an index of the string, and the charCodeAt method returns the Unicode of that character. If we don’t give anything inside that, it will return the Unicode of the first character of our string.
Converting string to charCode using map() function
The array map() function creates a new array populated with the results of calling a provided function on every element in the calling array.
const string_to_char_code = ([...string]) => {
const array = string.map((char) => {
return char.charCodeAt(0);
});
// array of unicode
return array;
}
console.log(string_to_char_code("Wonderful"));
Output
[87, 111, 110, 100, 101, 114, 102, 117, 108]
In the above example, we convert our whole string to an array of Unicode using a map, which is a simple way to do that.
Let’s do something interesting with that charCodeAt() method. In the below example, we do the sum of all Unicode.
const string_to_char_code = ([...string]) => {
const array = string.map(char => char.charCodeAt(0));
const sum = array.reduce((cur, prev) => cur + prev);
return sum;
}
console.log(string_to_char_code("Wonderful People"));
Output
1595
Converting a Unicode to char code
The String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.
Syntax
String.fromCharCode(P1, P2, …);
Parameters
P1, P2, P3: These methods need one or more Unicode values separated by commas.
Return value
String: It returns a string of Unicode, which we pass.
Example
const character = String.fromCharCode(86);
console.log(character);
const str = String.fromCharCode(87, 111, 110, 100, 101, 114, 102, 117, 108);
console.log(str)
Output
V
Wonderful
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.