How to reverse string in es6
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)}".
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');
Copy after login
function reverseString(str) { return str.split('').reverse().join(''); } reverseString('hello');
2. Reverse the string using a descending for loopfunction 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');
Copy after login
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');
Copy after login
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.
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"Copy after login
- The charAt() method returns the specified character from a string.
'hello'.charAt(0); // "h"
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');
Copy after login
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');
Copy after login
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
