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:
i
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.
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):
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.
The recursive method in the second part.
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
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
function reverseString (str) { for (var i = str.length - 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, str.length, '');}reverseString("hello"); // =>olleh
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
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
function reverseString(str) { return [].reduceRight.call(str, function(prev, curr) { return prev + curr; }, '');}reverseString("hello"); // =>olleh
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.