What is a string?
Reversing a String using Different Techniques:
Below are some of the ways to reverse a string:
Method 1: The manual approach:
Working of the below code:
- First, the program checks if the given string is empty, has one character, or is not of string type. It will return, “not valid”.
- If the string is not empty, a new array Rarray gets created to store the result.
- Then, the code iterates from the end of the array to the beginning and pushes each element into the new array (Rarray).
- Lastly, using the function join() to bind the elements in the array.
Method 2: using split() and reverse():
This method undergoes three simple steps:
- Split- The split() function divides the string into an array of characters.
- Reverse- Reversing the separated elements using the function reverse().
- Join- Lastly, merging all the characters into the string with the function join().
Method 3: Using the spread operator with split() and join() methods:
This method is just a little different from the second method:
- It splits the string into an array of characters using the spread operator instead of the split() function.
- The code then reverses the characters with the help of the reverse() function.
- Lastly, merging all the characters using the function join().
<script> const Rstring = str => [...str].reverse().join(''); //using the spread operator, and calling reverse(), join() function. document.write("Kindness is a great virtue") document.write("<br>") document.write( Rstring("Kindness is a great virtue") ) </script>
Often we require reversing a string in understanding long data, searching algorithms and competitive coding exams to check whether it’s a palindrome or a regular string. This article catered to some amazing ways to reverse the string using different methods and tactics.
Method 1 is comparatively more efficient because it uses less built-in methods than the second and third method. But there are various situations where the second and third methods are faster to write and use.