Home > Web Front-end > JS Tutorial > String reversal_JavaScript_javascript tips

String reversal_JavaScript_javascript tips

WBOY
Release: 2016-05-16 15:03:21
Original
1375 people have browsed it

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.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template