Home Web Front-end JS Tutorial String reversal_JavaScript_javascript tips

String reversal_JavaScript_javascript tips

May 16, 2016 pm 03:03 PM
String reverse

Today I was answering questions on freeCodeCamp and came across a question about string reversal. Reversing a string is one of the common interview questions in JavaScript. Maybe the interviewer will give you a string "Hello Word!" and ask you to use JavaScript to turn it into "!droW olleH".

I am also a beginner. Using the array-related knowledge I learned earlier and the tips on the question, I passed the test. Later, I thought, are there other ways to solve this question? After searching, there are still many methods. Here are these methods for future use.

Things to do

What we have to do:

To display the provided string in reverse before the reverse string, the string needs to be converted into an array. The final result is still a string

Next, let’s take a look at some methods to achieve the above requirements.

Use built-in functions

In the exercise question, we are reminded that we can use three methods to successfully display a string in reverse:

String.prototype.split()Array.prototype.reverse()Array.prototype.join()

Let’s go through it briefly:

The split() method splits each character of a string object and treats each string as each element of the array. The reverse() method is used to change the array and arrange the elements in the array in reverse order. The first array element becomes the last one, and the last one becomes the first one. The join() method connects all elements in the array into a string

Let’s look at an example:

function reverseString(str)
 { // 第一步,使用split()方法,返回一个新数组 
// var splitString = "hello".split(""); 
var splitString = str.split(""); 
//将字符串拆分 // 返回一个新数组["h", "e", "l", "l", "o"] 
// 第二步,使用reverse()方法创建一个新数组 
// var reverseArray = ["h", "e", "l", "l", "o"].reverse(); 
var reverseArray = splitString.reverse(); 
// 原数组元素顺序反转["o", "l", "l", "e", "h"] 
// 第三步,使用join()方法将数组的每个元素连接在一起,组合成一个新字符串 
// var joinArray = ["o", "l", "l", "e", "h"].join(""); 
var joinArray = reverseArray.join(""); // "olleh" 
// 第四步,返回一个反转的新字符串 return joinArray; 
// "olleh"}reverseString("hello"); 
// => olleh
Copy after login

Simplify the above method and write it like this:

function reverseString(str) {
 return str.split("").reverse().join("");
}reverseString("hello"); 
// => olleh
Copy after login

Reverse the string using a descending loop traversal

This method uses a for loop to perform a descending traversal of the original string, and then recombines the traversed strings into a new string:

function reverseString(str) { 
// 第一步:创建一个空的字符串用来存储新创建的字符串 var newString = ""; 
// 第二步:使用for循环 
// 循环从str.length-1开始做递减遍历,直到 i 大于或等于0,循环将继续
 // str.length - 1对应的就是字符串最后一个字符o for (var i = str.length - 1; i >= 0; i--) {
 newString += str[i]; // 或者 newString = newString + str[i]; } 
// 第三步:返回反转的字符串 return newString; }reverseString('hello'); 
// => // "olleh"
Copy after login

Simple look at the process of string traversal. Suppose you need to reverse the string "hello". The entire traversal process is shown in the following table:

Iteration order The value corresponding to i New string newString Each iteration str.length - 1 newString + str[i] First iteration 5 - 1 = 4 "" + "o" = "o" Second iteration 4 - 1 = 3 "o" + "l" = "ol" Third iteration 3 - 1 = 2 "ol" + "l" = "oll" Fourth iteration 2 - 1 = 1 "oll" + "e" = "olle" Fifth iteration Iteration 1 - 1 = 0 "olle" + "h" = "olleh"

In fact, the above for loop can also be replaced by a while loop:

function reverseString (str) {
 var newString = '';
 var i = str.length; while (i > 0) {
 newString += str.substring(i - 1, i);
 i--; 
} 
return newString;}reverseString("hello"); 
// => olleh
Copy after login

while method in substring() loop. substring() Returns the substring between two indices of the string (or to the end of the string).

Reverse string using recursion

A string can also be reversed using the String.prototype.substr() and String.prototype.charAt() methods.

The

substr() method returns the substring starting from the specified position to the specified length in the string. For example:

var str = "abcdefghij";
console.log("(1,2): " + str.substr(1,2));
 // (1,2): bcconsole.log("(-3,2): " + str.substr(-3,2));
 // (-3,2): hiconsole.log("(-3): " + str.substr(-3)); 
// (-3): hijconsole.log("(1): " + str.substr(1)); 
// (1): bcdefghijconsole.log("(-20, 2): " + str.substr(-20,2)); 
// (-20, 2): abconsole.log("(20, 2): " + str.substr(20,2)); 
// (20, 2):
Copy after login
The

charAt() method returns the character at the specified position in the string. Characters in a string are indexed from left to right, with the first character having index value 0 and the last character (assuming it is in the string stringName) having index value stringName.length - 1. If the specified index value is outside this range, an empty string is returned.

var anyString = "Brave new world";
console.log("The character at index 0 is '" + anyString.charAt(0) + "'"); 
// =>The character at index 0 is 'B'console.log("The character at index 1 is '" + anyString.charAt(1) + "'"); 
// =>The character at index 1 is 'r'console.log("The character at index 2 is '" + anyString.charAt(2) + "'"); 
// =>The character at index 2 is 'a'console.log("The character at index 3 is '" + anyString.charAt(3) + "'"); 
// => The character at index 3 is 'v'console.log("The character at index 4 is '" + anyString.charAt(4) + "'"); 
// => The character at index 4 is 'e'console.log("The character at index 999 is '" + anyString.charAt(999) + "'"); 
// => The character at index 999 is ''
Copy after login

Combined, we can do string reverse like this:

function reverseString(str) { if (str === "") { 
return ""; } else { 
return reverseString(str.substr(1)) + str.charAt(0); }
}reverseString("hello"); 
// => olleh
Copy after login

The first part of the recursive method. You need to remember that you won't just call it once, you will have several nested calls.

Each call to str === "?" reverseString(str.subst(1)) + str.charAt(0) The first time you call reverseString("Hello") reverseString("ello") + "h" The second time you call reverseString("ello") reverseString("llo") + "e" The third time Call reverseString("llo") reverseString("lo") + "l" The fourth call reverseString("lo") reverseString("o") + "l" The fifth call reverseString("o") reverseString(" ") + "o"

The recursive method in the second part.

every call Return the fifth call reverseString("") + "o" = "o" the fourth call reverseString("o") + "l" = "o" + "l" the third call reverseString("lo") + "l" = "o" + "l" + "l" The second call to reverserString("llo") + "e" = "o" + "l" + "l" + "e" The first call reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"

The above method can be further improved and changed to the ternary operator

function reverseString(str) { 
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);}
reverseString("hello"); 
// => olleh
Copy after login

You can also change it to this method

function reverseString(str) { 
return str && reverseString(str.substr(1)) + str[0];
}reverseString("hello");
 // => olleh
Copy after login

Other methods

In addition to the above methods, there are actually some other methods:

Method 1

Copy code The code is as follows:
function reverseString (str) { var newString = []; for (var i = str.length - 1, j = 0; i >= 0; i--, j++) { newString[j] = str[i]; } return newString.join('');}reverseString("hello"); // => olleh
Method 2
Copy codeThe code is as follows:
function reverseString (str) { for (var i = str.length - 1, newString = ''; i >= 0; newString += str[i--] ) { } return newString;}reverseString("hello"); // => olleh
Method Three
Copy code The code is as follows:
function reverseString (str) { function rev(str, len, newString) { return (len === 0) ? newString : rev(str, --len, (newString += str[len])); } return rev(str, str.length, '');}reverseString("hello"); // =>olleh
Method Four
Copy code The code is as follows:
function reverseString (str) { str = str.split(''); var len = str.length, halfIndex = Math.floor(len / 2) - 1, newString; for (var i = 0; i <= halfIndex; i++) { newString = str[len - i - 1]; str[len - i - 1] = str[i]; str[i] = newString; } return str.join('');}reverseString("hello"); // => olleh
Method 5
Copy codeThe code is as follows:
function reverseString (str) { if (str.length < 2) { return str; } var halfIndex = Math.ceil(str.length / 2); return reverseString(str.substr(halfIndex)) + reverseString(str.substr(0, halfIndex));}reverseString("hello"); // =>olleh
Method 6
Copy the codeThe code is as follows:
function reverseString(str) { return [].reduceRight.call(str, function(prev, curr) { return prev + curr; }, '');}reverseString("hello"); // =>olleh
ES6 method

In ES6, it can become simpler, such as:

[...str].reverse().join('');

or [...str].reduceRight( (prev, curr) => prev + curr );

or:

const reverse = str => str && reverse(str.substr(1)) + str[0];

String reversal is a small and simple algorithm. As mentioned before, it is often used in interviews with JavaScript basics. You can use various methods above to solve this problem, or even use more complex solutions. If you have a better method, please add it in the comments below and share it with us.

Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles