How do you reverse a string in place in JavaScript?

前端 未结 30 3164
猫巷女王i
猫巷女王i 2020-11-22 00:29

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

30条回答
  •  清歌不尽
    2020-11-22 00:49

    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.

    [...s] is Unicode aware, a small edit gives:-

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

提交回复
热议问题