Home >Web Front-end >JS Tutorial >How Can I Reverse a String in JavaScript In-Place Using Only Built-In Functions While Handling Unicode Correctly?

How Can I Reverse a String in JavaScript In-Place Using Only Built-In Functions While Handling Unicode Correctly?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 04:51:09317browse

How Can I Reverse a String in JavaScript In-Place Using Only Built-In Functions While Handling Unicode Correctly?

Reverse a String In-Place in JavaScript Using Built-In Functions

Problem:

Consider a string passed to a function that returns the reversed string. How can this be achieved in JavaScript using built-in functions and without relying on methods like .reverse() or .charAt()?

Solution:

Unicode-Aware Solution:

For strings containing simple ASCII characters, the following function utilizes built-in functions:

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

However, for strings containing multi-byte characters (such as UTF-16), this solution will return invalid unicode strings or strings that appear distorted. To address this, consider the following alternative approaches:

Using Array Expansion Operator:

The array expansion operator is Unicode-aware, allowing for the following reversal function:

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

Using Split() with RegExp and Unicode Flag:

Another Unicode-aware approach is to use split() with a regular expression and the Unicode flag (u) as the separator:

function reverse(s) {
  return s.split(/(?:)/u).reverse().join("");
}

The above is the detailed content of How Can I Reverse a String in JavaScript In-Place Using Only Built-In Functions While Handling Unicode Correctly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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