=0;i--){nS+=str[i];}"; 3. Use recursion, the syntax "function f(s){return s===''?'':f (s.substr(1))+s.charAt(0)}"."/> =0;i--){nS+=str[i];}"; 3. Use recursion, the syntax "function f(s){return s===''?'':f (s.substr(1))+s.charAt(0)}".">

Home >Web Front-end >Front-end Q&A >How to reverse string in es6

How to reverse string in es6

青灯夜游
青灯夜游Original
2022-10-31 19:02:141295browse

Implementation method: 1. Use the split, reverse and join functions, the syntax "str.split('').reverse().join('');"; 2. Use the descending for loop, the syntax "for(i=string length-1;i>=0;i--){nS =str[i];}"; 3. Use recursion, the syntax "function f(s){return s===' '?'':f(s.substr(1)) s.charAt(0)}".

How to reverse string in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Reverse a string is one of the most frequently asked JavaScript questions in technical interviews. The interviewer may ask you to use a different encoding to reverse the string, or they may ask you not to use the built-in method to reverse the string, or even ask you to use recursion to reverse the string.

There are probably dozens of different ways to do this, with the exception of the built-in reverse method, since there is no such method on JavaScript's String object

Here's how I solved it Three most interesting ways to reverse string problems in JavaScript.

Algorithm requirements

Reverse the supplied string.
You may need to convert the string to an array before you can reverse it.
Your result must be a string.

function reverseString(str) {
    return str;
}
reverseString('hello');

Provide test cases

  • reverseString(“hello” ) should return "olleh"
  • reverseString("Howdy") should return "ydwoH"
  • reverseString("Greetings from Earth") should return "htraE morf sgniteerG"

1. Use built-in methods to reverse the string

For this solution, we will use three methods: String.prototype.split() method, Array.prototype.reverse() method and Array.prototype.join() method.

  • The split() method uses the specified delimiter string to split a String object into an array of substrings, and uses a specified split string to determine the position of each split
  • ## The #reverse() method reverses the position of elements in an array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method will change the original array. The
  • join() method joins all elements of an array (or an array-like object) into a string and returns this string. If the array has only one item, then the item will be returned without using the separator
  • function reverseString(str) {
        // Step 1. 使用 split()方法返回一个新数组
        var splitString = str.split(''); // var splitString = "hello".split("");
        // ["h", "e", "l", "l", "o"]
    
        // Step 2.使用 reverse()方法 翻转数组
        var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
        // ["o", "l", "l", "e", "h"]
    
        // Step 3.使用 join()方法 组合所有的数组元素,从而变成一个新字符串
        var joinArray = reverseArray.join(''); // var joinArray = ["o", "l", "l", "e", "h"].join("");
        // "olleh"
    
        //Step 4. 返回翻转后的字符串
        return joinArray; // "olleh"
    }
    
    reverseString('hello');

The three methods are combined to form a chain call:
function reverseString(str) {
    return str.split('').reverse().join('');
}
reverseString('hello');

2. Reverse the string using a descending for loop
function reverseString(str) {
    // Step 1. 创建一个空字符串,用来存储后面新创建的字符串
    var newString = '';

    // Step 2.创建for循环
    /* 循环的起点是(str.length-1),它对应于
        字符串的最后一个字符“o”
        只要i大于或等于0,循环就会继续
        每次迭代后递减i */
    for (var i = str.length - 1; i >= 0; i--) {
        newString += str[i]; // or newString = newString + str[i];
    }
    /* "hello"的length等于 5
        每次循环的公式: i = str.length - 1 and newString = newString + str[i]
        第一次循环:   i = 5 - 1 = 4,         newString = "" + "o" = "o"
        第二次循环:   i = 4 - 1 = 3,         newString = "o" + "l" = "ol"
        第三次循环:   i = 3 - 1 = 2,         newString = "ol" + "l" = "oll"
        第四次循环:   i = 2 - 1 = 1,         newString = "oll" + "e" = "olle"
        第五次循环:   i = 1 - 1 = 0,         newString = "olle" + "h" = "olleh"
    结束for循环*/

    // Step 3. 返回已翻转的字符串
    return newString; // "olleh"
}

reverseString('hello');

Remove comments:
function reverseString(str) {
    var newString = '';
    for (var i = str.length - 1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}
reverseString('hello');

3. Reverse the string using recursion

For this solution, we will use two methods: String.prototype.substr() method and String.prototype.charAt() method

    The substr() method returns the characters starting from the specified position to the specified number of characters in a string.
Translator's Note:

Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided if possible. It is not part of the core JavaScript language and may be removed in the future. If possible, use substring() instead.

'hello'.substr(1); // "ello"
    The charAt() method returns the specified character from a string.
  • 'hello'.charAt(0); // "h"
Recursive The depth is equal to the length of the String. When the String is very long and stack size is the main issue, the code runs very slowly. So this solution is not the best solution

function reverseString(str) {
  if (str === "") // 如果传入空字符串,则直接返回它
    return "";
  else
    return reverseString(str.substr(1)) + str.charAt(0);
/*
递归方法的第一部分
你需要记住不会只有一次回调,会存在多次嵌套回调
每次回调的公式: str === "?"                         reverseString(str.subst(1))     + str.charAt(0)
1st call – reverseString("Hello")   will return   reverseString("ello")           + "h"
2nd call – reverseString("ello")    will return   reverseString("llo")            + "e"
3rd call – reverseString("llo")     will return   reverseString("lo")             + "l"
4th call – reverseString("lo")      will return   reverseString("o")              + "l"
5th call – reverseString("o")       will return   reverseString("")               + "o"
递归方法的第二部分
该方法达一旦到if条件,嵌套最深的调用会立即返回
*/

Delete comment:
function reverseString(str) {
    if (str === '') return '';
    else return reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('hello');

Use ternary expression:
function reverseString(str) {
    return str === '' ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('hello');

JavaScript String Reverse is a small and simple algorithm that you may be asked about in a technical phone screen or technical interview. You can solve this problem in the simplest way, or with a recursive or more complex solution.

【Related recommendations:

javascript video tutorial, programming video

The above is the detailed content of How to reverse string in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn