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.
Using built-in functions
In the exercises, we are prompted that we can use three methods to successfully display a string in reverse:
String.prototype.split()Array.prototype.reverse()Array.prototype.join()
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 = str.split(""); //Split the string // Return a new array ["h", "e", "l", "l", "l", "o"] // The second step is to use the reverse() method to create a new array // var reverseArray = ["h", "e", "l", "l", "o"].reverse(); var reverseArray = splitString.reverse(); // The original array elements are reversed in sequence ["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 = reverseArray.join(""); // "olleh" // The fourth step is to return a new string that is reversed. return joinArray; // "olleh"}reverseString("hello"); // => ollehSimplify the above method and can be written like this:
function reverseString(str) { return str.split("").reverse().join("");}reverseString("hello"); // => ollehInvert the string using a decreasing loop traversal
This method uses a for loop to perform 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 // Loop starts decreasing traversal from str.length-1 until i is greater than or equal to 0, the loop will continue // str.length - 1 corresponds to the last character of the string o for (var i = str.length - 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 In fact, the for loop above can also be replaced with 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 substring() method in while loop. substring() returns a substring between two indexes of the string (or to the end of the string).
Implement string inversion using recursion
A string can also be reversed using String.prototype.substr() and String.prototype.charAt() methods.
substr() method returns a substring in the string starting from the specified position to the specified length. for example:
var str = "abcdefghij";console.log("(1,2): " + str.substr(1,2)); // (1,2): bcdefghijconsole.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): charAt() method returns the character at the specified position in the string. Characters in the string are indexed from left to right, the first character has an index value of 0 and the last character (assuming that character is in the string stringName ) has an index value of 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 this to implement string inversion:
function reverseString(str) { if (str === "") { return ""; } else { return reverseString(str.substr(1)) + str.charAt(0); }}reverseString("hello"); // => ollehThe 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(str.substr(1)) + str.charAt(0);}reverseString("hello"); // => ollehIt can also be changed to this method
function reverseString(str) { return str && reverseString(str.substr(1)) + str[0];}reverseString("hello"); // => ollehOther methods
In addition to the above methods, there are actually some other methods:
Method 1 copy code 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 is as follows: function reverseString (str) { for (var i = str.length - 1, newString = ''; i >= 0; newString += str[i--] ) { } return newString;}reverseString("hello"); // => olleh method 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 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 five copy code 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 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 be made 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 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.