How do you reverse a string in place in JavaScript?

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

    OK, pretty simple, you can create a function with a simple loop to do the string reverse for you without using reverse(), charAt() etc like this:

    For example you have this string:

    var name = "StackOverflow";
    

    Create a function like this, I call it reverseString...

    function reverseString(str) {
      if(!str.trim() || 'string' !== typeof str) {
        return;
      }
      let l=str.length, s='';
      while(l > 0) {
        l--;
        s+= str[l];
      }
      return s;
    }
    

    And you can call it like:

    reverseString(name);
    

    And the result will be:

    "wolfrevOkcatS"
    

提交回复
热议问题