How do you reverse a string in place in JavaScript?

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

    I know that this is an old question that has been well answered, but for my own amusement I wrote the following reverse function and thought I would share it in case it was useful for anyone else. It handles both surrogate pairs and combining marks:

    function StringReverse (str)
    {
      var charArray = [];
      for (var i = 0; i < str.length; i++)
        {
          if (i+1 < str.length)
            {
              var value = str.charCodeAt(i);
              var nextValue = str.charCodeAt(i+1);
              if (   (   value >= 0xD800 && value <= 0xDBFF
                      && (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
                  || (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
                {
                  charArray.unshift(str.substring(i, i+2));
                  i++; // Skip the other half
                  continue;
                }
            }
    
          // Otherwise we just have a rogue surrogate marker or a plain old character.
          charArray.unshift(str[i]);
        }
    
      return charArray.join('');
    }
    

    All props to Mathias, Punycode, and various other references for schooling me on the complexities of character encoding in JavaScript.

    0 讨论(0)
  • 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("");
    }
    
    0 讨论(0)
  • 2020-11-22 00:49

    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                                                                     
    0 讨论(0)
  • 2020-11-22 00:50

    The whole "reverse a string in place" is an antiquated interview question C programmers, and people who were interviewed by them (for revenge, maybe?), will ask. Unfortunately, it's the "In Place" part that no longer works because strings in pretty much any managed language (JS, C#, etc) uses immutable strings, thus defeating the whole idea of moving a string without allocating any new memory.

    While the solutions above do indeed reverse a string, they do not do it without allocating more memory, and thus do not satisfy the conditions. You need to have direct access to the string as allocated, and be able to manipulate its original memory location to be able to reverse it in place.

    Personally, i really hate these kinds of interview questions, but sadly, i'm sure we'll keep seeing them for years to come.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-22 00:51

    You can't because JS strings are immutable. Short non-in-place solution

    [...str].reverse().join``
    

    let str = "Hello World!";
    let r = [...str].reverse().join``;
    console.log(r);

    0 讨论(0)
提交回复
热议问题