Reputation: 3129
I have converted a string into their ascii using string.charCodeAt(), but now that I have completed adding/subtracting the values I want to convert them from ASCII back to letters and a string.
I am looking to convert the following array back into their char letters and eventually a string using JavaScript.
asciiKeys= [70, 69, 69, 69, 32, 67, 66, 68, 69, 32, 67, 65, 77, 67];
I tried using the following, but it keeps stating that it is not a function:
for (var j=0;j<str.length;j++){
newAsciikeys.push(asciiKeys[j].fromCharCode(0));
}
Upvotes: 6
Views: 8484
Reputation: 22876
On modern browsers (not IE) it can be shortened with the Spread syntax :
s = "ABC", j = JSON.stringify
a = [...s].map(s => s.charCodeAt()) // string to array ( [...s] is short for s.slice() )
r = String.fromCharCode(...a) // array to string ( (...a) is short for .apply(0, a) )
console.log(j(s), j(a), j(r))
Upvotes: 0
Reputation: 3716
fromCharCode
is a static function on String
. So, this will do what you need, without the need for the loop:
reconstituted = String.fromCharCode.apply(null, asciiKeys);
The apply
function is how one sends an array of items to a function as if you had typed in each argument manually. e.g., String.fromCharCode( asciiKeys[0], asciiKeys[1], asciiKeys[2], asciiKeys[3], ... )
(Note that I'm assuming you don't need the intermediate array of characters, and this solution goes straight to the final string you request. If you yet want the intermediate array of characters, you can split the resulting array with reconstituted.split('')
.)
EDIT: (with thanks to @Kaiido)
For robustness sake, be aware that .apply
has a JS engine-specific limit to the number of arguments (read: array size) it can handle. To handle those situations, consider splitting up your work, or falling back to the trusty old loop with one-by-one processing.
Upvotes: 12
Reputation: 1
The value within the array needs to be passed to .fromCharCode()
; .fromCharCode()
is not .charCodeAt()
String.fromCharCode.apply(String, asciiKeys)
Alternatively you can use TextDecoder()
to convert an ArrayBuffer
representation of array to a string. If expected result is an array you can use spread element to convert string to array.
var asciiKeys = [70, 69, 69, 69, 32, 67, 66, 68, 69, 32, 67, 65, 77, 67];
var str = new TextDecoder().decode(Uint8Array.from(asciiKeys));
console.log(str, [...str]);
Upvotes: 2