Home > Web Front-end > JS Tutorial > How to Reverse a String In-Place in JavaScript?

How to Reverse a String In-Place in JavaScript?

Linda Hamilton
Release: 2024-12-15 16:25:15
Original
730 people have browsed it

How to Reverse a String In-Place in JavaScript?

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:

  • Convert to Array: Use the split('') function to convert the string into an array of characters.
  • Reverse Array: Utilize the reverse() method on the resulting array to reverse the order of characters.
  • Join Array: Finally, use the join('') function to concatenate the reversed characters back into a string.

Example 1 (ASCII Characters):

function reverse(s) {
    return s.split("").reverse().join("");
}

const original = "Hello";
const reversed = reverse(original);
console.log(reversed); // "olleH"
Copy after login

Example 2 (Unicode Support):

For strings containing multi-byte characters (e.g., UTF-16), a Unicode-aware solution is necessary.

  • Use Array Expansion Operator: The ... operator (spread operator) creates a new array with individual characters. This supports Unicode characters and yields valid unicode strings.
function reverse(s) {
    return [...s].reverse().join("");
}
Copy after login
  • Split with Unicode Flag: Alternatively, you can use split() with the u (Unicode) flag as a separator, which also supports Unicode characters.
function reverse(s) {
    return s.split(/(?:)/u).reverse().join("");
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template