How do you reverse a string in-place?

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("");
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)