Today I was practicing the question on freeCodeCamp, and I encountered a question about string inversion. Reversing a string is one of the common interview questions in JavaScript. Maybe the interviewer will give you a string "Hello Word!", which will allow you to turn it into "!droW olleH" through JavaScript.
I am also a beginner. I have passed the test using the knowledge related to the arrays I learned before and the tips on the questions. Later I wondered, is there any other way to solve this problem? After searching, there are still many methods. Here are some of these methods for later use.
Things to do
Things we want to do:
Before displaying the provided string in reverse before the reverse string, you need to convert the string into an array and the final result is still a string.
Next, let’s take a look at what methods can achieve the above requirements.
Use built-in functions
In the exercises, we are prompted that we can use three methods to successfully display a string in reverse:
()()()
Just go through it briefly:
Split() method splits out each character of a string object, and treats each string as each element of an array, reverses() method to change the array, arranges the elements in the array in reverse order, the first array element becomes the last, and the last one becomes the first join() method connects all elements in the array into a string
Let’s take a look at an example:
function reverseString(str) { // The first step is to use the split() method to return a new array// var splitString = "hello".split(""); var splitString = (""); //Split the string // Return a new array ["h", "e", "l", "l", "o"]// The second step is to create a new array using reverse() method// var reverseArray = ["h", "e", "l", "l", "o"].reverse(); var reverseArray = (); // The order of the original array elements is reversed ["o", "l", "l", "e", "h"]// The third step is to use the join() method to join each element of the array and combine it into a new string// var joinArray = ["o", "l", "l", "e", "h"].join(""); var joinArray = (""); // "olleh" // Step 4, return a new inverted string return joinArray;// "olleh"}reverseString("hello"); // => olleh
Simplify the above method and can be written like this:
function reverseString(str) { return ("").reverse().join(""); }reverseString("hello"); // => olleh
Invert the string using a decreasing loop traversal
This method uses afor
Looping to do a decremented traversal to the original string, and then re-merge the traversed string into a new string:
function reverseString(str) { // Step 1: Create an empty string to store the newly created string var newString = "";// Step 2: Use the for loop// The loop starts with -1 and performs decreasing traversal until i is greater than or equal to 0, and the loop will continue // - 1 corresponds to the last character of the string o for (var i = - 1; i >= 0; i--) { newString += str[i]; // Or newString = newString + str[i]; }// Step 3: Return the reversed string return newString; }reverseString('hello');// => // "olleh"
A simple look at the process of string traversal. Suppose you need to invert the string "hello". The entire traversal process is shown in the following table:
i
Value ofActually, the abovefor
Circulation can also be replaced withwhile
cycle:
function reverseString (str) { var newString = ''; var i = ; while (i > 0) { newString += (i - 1, i); i--; } return newString;}reverseString("hello"); // => olleh
existwhile
In the loopsubstring()
method.substring()
Returns a substring between two indexes of the string (or to the end of the string).
Implement string inversion using recursion
use()
and()
Methods can also reverse a string.
substr()
Method returns a substring in the string starting from the specified position to the specified length. for example:
var str = "abcdefghij"; ("(1,2): " + (1,2)); // (1,2): ("(-3,2): " + (-3,2)); // (-3,2): ("(-3): " + (-3)); // (-3): ("(1): " + (1)); // (1): ("(-20, 2): " + (-20,2)); // (-20, 2): ("(20, 2): " + (20,2)); // (20, 2):
charAt()
Method returns the character at the specified position in the string. The characters in the string are indexed from left to right, and the index value of the first character is0
, the last character (assuming that character is in the stringstringName
The index value of - 1
. If specifiedindex
If the value is outside this range, an empty string is returned.
var anyString = "Brave new world"; ("The character at index 0 is '" + (0) + "'"); // =>The character at index 0 is 'B'("The character at index 1 is '" + (1) + "'"); // =>The character at index 1 is 'r'("The character at index 2 is '" + (2) + "'"); // =>The character at index 2 is 'a'("The character at index 3 is '" + (3) + "'"); // => The character at index 3 is 'v'("The character at index 4 is '" + (4) + "'"); // => The character at index 4 is 'e'("The character at index 999 is '" + (999) + "'"); // => The character at index 999 is ''
Combined, we can do this to implement string inversion:
function reverseString(str) { if (str === "") { return ""; } else { return reverseString((1)) + (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.
Part 2 recursive method.
The above method can be further improved and changed to a ternary operator
function reverseString(str) { return (str === '') ? '' : reverseString((1)) + (0);} reverseString("hello"); // => olleh
It can also be changed to this method
function reverseString(str) { return str && reverseString((1)) + str[0]; }reverseString("hello"); // => olleh
Other methods
In addition to the above methods, there are actually some other methods:
Method 1
function reverseString (str) { var newString = []; for (var i = - 1, j = 0; i >= 0; i--, j++) { newString[j] = str[i]; } return ('');}reverseString("hello"); // => olleh
function reverseString (str) { for (var i = - 1, newString = ''; i >= 0; newString += str[i--] ) { } return newString;}reverseString("hello"); // => olleh
function reverseString (str) { function rev(str, len, newString) { return (len === 0) ? newString : rev(str, --len, (newString += str[len])); } return rev(str, , '');}reverseString("hello"); // =>olleh
function reverseString (str) { str = (''); var len = , halfIndex = (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 ('');}reverseString("hello"); // => olleh
function reverseString (str) { if ( < 2) { return str; } var halfIndex = ( / 2); return reverseString((halfIndex)) + reverseString((0, halfIndex));}reverseString("hello"); // =>olleh
function reverseString(str) { return [].(str, function(prev, curr) { return prev + curr; }, '');}reverseString("hello"); // =>olleh
In ES6, it can be made simpler, such as:
[...str].reverse().join('');
or[...str].reduceRight( (prev, curr) => prev + curr );
or:
const reverse = str => str && reverse((1)) + str[0];
String inversion is a small and simple algorithm, as mentioned earlier, and is often used to interview basic JavaScript. You can use the above methods to solve this problem, or even use more complex solutions. If you have a better way, please add it in the comments below and share it with us.