search
HomeWeb Front-endJS TutorialString reversal_JavaScript_javascript tips

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

Simplify the above method and write it like this:

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

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"

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

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):
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 ''

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

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

You can also change it to this method

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

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 olleh
Method 5
Copy codeThe code is as follows:
function reverseString (str) { if (str.length 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
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
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),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool