- Three Ways to Reverse a String in JavaScript
- By Sonya Moisset
- Translator: @yuebai
- Reviewer:
Inverting strings is one of the most frequently asked JavaScript questions in technical interviews. The interviewer may ask you to use a different encoding to reverse the string, or they may ask you not to use the built-in method to reverse the string, or they may even ask you to use recursive inversion.
There are probably dozens of different ways to do this, except for the built-in Reverse method, which doesn’t exist on JavaScript strings
Here are three of my most interesting ways to solve the JavaScript inversion string problem.
Algorithms require
Inverts the supplied string. You may need to convert a string to an array before you can reverse it. Your result must be a string.
function reverseString(str) {
return str;
}
reverseString('hello');
Copy the code
Provide test cases
- ReverseString (” hello “) should return “olleh”
- ReverseString (” Howdy “) should return “ydwoH”
- ReverseString (” Greetings from Earth “) should return “htraE morf sgniteerG”
1. Use the built-in method to reverse the string
For this solution, we will use three methods: the string.prototype.split () method, the array.prototype.reverse () method, and the array.prototype.join () method.
- The split() method splits a String into an array of substrings using the specified delimiter String, with a specified split String to determine the location of each split
- The reverse() method reverses the positions of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the array
- The join() method joins all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, the item is returned without a delimiter
function reverseString(str) {
Return a new array using the split() method
var splitString = str.split(' '); // var splitString = "hello".split("");
// ["h", "e", "l", "l", "o"]
// Step 2. Reverse the array using the reverse() method
var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
// ["o", "l", "l", "e", "h"]
// Step 3. Use the join() method to combine all the array elements into a new string
var joinArray = reverseArray.join(' '); // var joinArray = ["o", "l", "l", "e", "h"].join("");
// "olleh"
//Step 4. Return the reversed string
return joinArray; // "olleh"
}
reverseString('hello');
Copy the code
The three methods are combined to form a chained call:
function reverseString(str) {
return str.split(' ').reverse().join(' ');
}
reverseString('hello');
Copy the code
2. Invert the string with a decrement for loop
function reverseString(str) {
// Step 1. Create an empty string to store the newly created string
var newString = ' ';
Step 2. Create a for loop
/* The starting point of the loop is (str.length-1), which corresponds to the last character of the string, "o", as long as I is greater than or equal to 0, the loop continues to decrement by I */ after each iteration
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i]; // or newString = newString + str[i];
}
/* newString = newString + STR [I]; /* newString = newString + STR [I]; I = = 4, 5-1 newString = "" +" o "=" o "in the second cycle: I = = 3, 4-1 newString =" o "+" l "=" ol "third cycle: I = 2-1 = 1, newString = "oll" + "e" = "olle" I = 1-1 = 0, newString = "olle" + "h" = "olleh" ends the for loop */
// Step 3. Return the reversed string
return newString; // "olleh"
}
reverseString('hello');
Copy the code
Delete comments:
function reverseString(str) {
var newString = ' ';
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}
reverseString('hello');
Copy the code
3. Recursively reverse the string
For this solution, we will use two methods: the string.prototype.substr () method and the string.prototype.charat () method
- The substr() method returns a string of characters from the specified position to the specified number of characters.
The translator’s note:
Although String. Prototype. Substr (…) It is not strictly removed (as in “removed from the Web Standards “), but it is considered a legacy function and should be avoided if possible. It is not part of the JavaScript core language and may be removed in the future. If you can, use substring() instead.
'hello'.substr(1); // "ello"
Copy the code
- The charAt() method returns the specified character from a string.
'hello'.charAt(0); // "h"
Copy the code
The depth of the recurrence is equal to the length of the String. When the String is long and stack size is the main issue, the code runs very slowly. So this is not the best solution
function reverseString(str) {
if (str === "") // If an empty string is passed, return it directly
return "";
else
return reverseString(str.substr(1)) + str.charAt(0);
/* For the first part of recursion methods you need to remember that there is not only one callback, there is a formula for nesting multiple callbacks each time: STR === "?" ReverseString (str.subst(1)) + str.charat (0) 1st call -- reverseString("Hello") will return reverseString("ello") + "h" 2nd Call -- reverseString("ello") + "e" 3rd Call -- reverseString(" lLO ") will return ReverseString ("lo") + "l" 4th call -- reverseString("lo") will return reverseString("o") + "l" 5th call -- reverseString("lo") + "l" 4th call ReverseString ("o") will return the second part of the recursive method reverseString("") + "o"Copy the code
Delete comments:
function reverseString(str) {
if (str === ' ') return ' ';
else return reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('hello');
Copy the code
Using ternary expressions:
function reverseString(str) {
return str === ' ' ? ' ' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('hello');
Copy the code
JavaScript string inversion is a small and simple algorithm that can be asked in a telephone technology screening or a technical interview. You can solve this problem in the simplest way, or you can solve it recursively or with more complex solutions.
Hopefully this post was helpful, and if you have your own solutions or any suggestions, feel free to leave them in the comments.
# Stay curious, # Keep moving and # achieve!
resources
- The split () method – MDN
- The reverse () method — MDN
- The join () method — MDN
- String. The length of the MDN
- The substr () method — MDN
- The charAt () method — MDN