Checkout this video:
We’ll discuss the different methods available to us, their syntax, and when to use them. We’ll also touch on some of the potential problems that can occur when reversing strings.
Reversing a String With the Built-In Functions
The split() Function
The split() function is used to split a string into an array of substrings, and returns the new array. The original string is not modified.
If you specify a separator string, then the split() function will use that string to divide the original string into substrings. For example, if you have a list of items in a CSV file, and you want to divide each item into its own substring, then you can use the comma (,) as the separator string:
var str = “1,2,3,4”;
var arr = str.split(“,”);
// arr = [“1”, “2”, “3”, “4”];
The reverse() Function
var str = “Hello world!”;
var reverseStr = str.reverse();
console.log(reverseStr); //outputs “!dlrow olleH”
You can also use the built-in split() and join() functions to reverse a string:
var str = “Hello world!”;
var splitStr = str.split(“”); //split the string into an array of characters
var reverseSplitStr = splitStr.reverse(); //reverse the order of the array
var joinSplitStr = reverseSplitStr.join(“”); //join the characters back into a string
console.log(joinSplitStr); //outputs “!dlrow olleH”
The join() Function
To use the join Function to reverse a string, you need to first split the string into an array of characters using the split Function. Then, you can pass the array of characters into the join Function, with the separator set to an empty string (“”). This will concatenate all of the characters in the array together into a single string, in reverse order.
Here is an example of how to use the join Function to reverse a string:
var str = “Hello World!”;
var revStr = str.split(“”).join(“”); // Split each character into an array, then join with no separator
console.log(revStr); // Output: “!dlroW olleH”
As you can see from the example above, reversing a string with the built-in functions is quite simple. However, there are other ways to achieve this as well.
Reversing a String Without the Built-In Functions
The for Loop
To reverse a string, you need to:
-Declare an empty string that will hold the reversed string.
-Use a for loop to iterate over the characters in the original string, starting from the end.
-At each iteration, add the character to the reversed string.
-After the loop finishes, return the reversed string.
The while Loop
The while loop will keep looping through the code as long as the condition is true. In this case, we want to keep looping until the value of i is no longer less than the length of the string. Once i is equal to or greater than the length of the string, we want to stop looping.