How do you reverse a string in place in JavaScript?

前端 未结 30 3271
猫巷女王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:42

    I think String.prototype.reverse is a good way to solve this problem; the code as below;

    String.prototype.reverse = function() {
      return this.split('').reverse().join('');
    }
    
    var str = 'this is a good example for string reverse';
    str.reverse();
    -> "esrever gnirts rof elpmaxe doog a si siht";
    

提交回复
热议问题