=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)}".">
search
HomeWeb Front-endFront-end Q&AHow to reverse string in es6
How to reverse string in es6Oct 31, 2022 pm 07:02 PM
javascriptes6es6 string

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools