DEV Community

Muhammad    Uzair
Muhammad Uzair

Posted on

Reversing a String

Reverse string using the split, reverse, and join methods.
If an exception is thrown, catch it and print the contents of the exception's on a new line.
Print on a new line. If no exception was thrown, then this should be the reversed string; if an exception was thrown, this should be the original string.

 function reverseString(s) {
try {
let reversString = s.split("").reverse()
console.log(reversString.join(""))

}
catch (e) {
console.log(e.message);
console.log(s)
}

}




Explanation:

-The split method converts the string into array.
-The reverse methods reverse the entries of an array.
-The Join methods finally prints the array entries with joining
them according to the condition you pass in parenthesis.

Output:

     reverseString("1234")
Output = 4321




Try,Catch

I have used this try catch because if the data type will be other than string so the split function will not be applicable it will give runtime error,But in my case if there will be any error it will sent to catch block rather than displaying runtime error it will display a message.

Hope you find this helpful.

Happy Coding!

Top comments (0)