In the following example, we have one global string. We will pass it to our custom method to reverse the order of letters and log the final string in the console window. Please have a look over the code example and the steps given below.
HTML & CSS
We do not have any element in the HTML file because it is not required for this tutorial.
We have a global variable myMsg and it holds a string.
We have created a custom method reverseString() which takes a string as a parameter.
Inside the reverseString() method, we are splitting the string using the split() method. We are doing so to get rid of spaces in the string. This method will return an array of words and we are storing that array in the step1 variable.
We are using the map() method to iterate over each word. Inside this method, we are using the split() method with each word to get an array of letters. We are reversing the order of this array by calling the reverse() method and we are joining it back by calling the join() method.
The map() method returns an array and we are storing that in step2 variable.
So far letters in each word have been reversed, but we also need to reverse the order of words in the string. We are calling the reverse() method to reverse the order of words and storing the returned array in the step3 variable.
We have to convert the array into a string and that is why we are calling the join() method and passing a space as a parameter. This will result in a space between each word. We are storing the final string in step4 variable and returning it.
We are calling the reverseString() method and passing string myMsg as a parameter. We are logging the string returned by this method in the console window by using the console.log() method.
const myMsg = 'Hello World';
let step1 = msg.split(' ');
let step2 = step1.map(word => word.split('').reverse().join(''));
let step3 = step2.reverse();
let step4 = step3.join(' ');