admin管理员组

文章数量:1126304

How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse(), .charAt() etc.)?

How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse(), .charAt() etc.)?

Share Improve this question edited Oct 25, 2023 at 22:57 Trenton McKinney 62.2k41 gold badges164 silver badges190 bronze badges asked Jun 6, 2009 at 3:14 JakeJake 8
  • so, you're not allowed to use .charAt() to get the characters of the string? – Irwin Commented Jun 6, 2009 at 3:27
  • 192 You can't. JavaScript strings are immutable, meaning the memory allocated to each cannot be written to, making true "in place" reversals impossible. – Crescent Fresh Commented Jun 6, 2009 at 4:36
  • 3 Re: crescentfresh's comment see stackoverflow.com/questions/51185/… – baudtack Commented Jun 6, 2009 at 5:25
  • 3 @crescentfresh you should post that as a new answer. – baudtack Commented Jun 6, 2009 at 5:47
  • 2 Reverse a string in 3 ways in Javascript – Somnath Muluk Commented Sep 12, 2016 at 7:12
 |  Show 3 more comments

59 Answers 59

Reset to default 1 2 Next 1006

As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:

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

If you need a solution that supports UTF-16 or other multi-byte characters, be aware that this function will give invalid unicode strings, or valid strings that look funny. You might want to consider this answer instead.

The array expansion operator is Unicode aware:

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

Another Unicode aware solution using split(), as explained on MDN, is to use a regexp with the u (Unicode) flag set as a separator.

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

The following technique (or similar) is commonly used to reverse a string in JavaScript:

// Don’t use this!
var naiveReverse = function(string) {
    return string.split('').reverse().join('');
}

In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:

naiveReverse('foo 

本文标签: javascriptHow do you reverse a string inplaceStack Overflow