In-Place String Reversal in JavaScript
When working with strings in JavaScript, there may be situations where you need to reverse a string in-place without relying on built-in functions like .reverse() or .charAt(). This can be achieved when the string is passed to a function with a return statement.
To reverse a string in-place:
Example 1 (ASCII Characters):
function reverse(s) { return s.split("").reverse().join(""); } const original = "Hello"; const reversed = reverse(original); console.log(reversed); // "olleH"
Example 2 (Unicode Support):
For strings containing multi-byte characters (e.g., UTF-16), a Unicode-aware solution is necessary.
function reverse(s) { return [...s].reverse().join(""); }
function reverse(s) { return s.split(/(?:)/u).reverse().join(""); }
By implementing these solutions, you can effectively reverse a string in-place within a function, regardless of the character set used.
The above is the detailed content of How to Reverse a String In-Place in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!