function reverseString(str) {
return str.split("").reverse().join("");
}
let reversedString = reverseString("Hello, 👋!");
console.log(reversedString);
This bug occurs because the split method treats the string as an array of 16-bit units, not as an array of characters resulting the unexpected output: !�� ,olleH. By using Array.from(str) or [...str] the string is split into an array of actual characters, respecting the surrogate pairs.
Using Array.from:
function reverseString(str) {
return Array.from(str).reverse().join("");
}
let reversedString = reverseString("Hello, 👋!");
console.log(reversedString);
Using the spread operator:
function reverseString(str) {
return [...str].reverse().join("");
}
let reversedString = reverseString("Hello, 👋!");
console.log(reversedString);