How to reverse strings and numbers is a common question asked in interviews so, I decided to write an article on it, and is the first article on hashnode for me...!! first, we need to understand the basic fundamentals of string, so let's start with the introduction.
What is a string?
The string is a sequence of one or more characters, strings are primary data types in javascript and they are immutable (unchanging), to reverse a string we need to know about some methods like split(), reverse(), and join(). we can also reverse strings by other methods like loops and conditional methods and we will look at them step by step in this article.
Reverse string with in-built methods
- Split(): A string can be converted to an array with this method:
- reverse(): method reverses the order of the elements in an array.
- join(): method returns an array as a string.
Example of reverse string
const str = "hashnode is awesome"
function reverseAString(str) {
return str.split("").reverse("").join("");
}
console.log(`Reversed string is: ${reverseAString(str)}`)
Now we reverse a string using in-built but we can reverse string with loops to here how we can do it
function reverseString(str) {
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}
reverseString('hello hashnode');
Here is how we can reverse string with in-built and without in-built methods. Now we see how to reverse numbers in javascript.
const num = 3849;
function reverseGivenInteger(num) {
// write your solution here
return (
parseFloat(
num
.toString()
.split('')
.reverse('')
.join('')
) *Math.sign(num)
)
}
console.log(`Reversed integer is: ${reverseGivenInteger(num)}`)
This is how we can reverse strings and numbers in javascript. This is a simple javascript algorithm that might be asked in technical interview questions so you have to find the shortest route to do it. I hope you found this helpful.
Hey, I'm Ganesh ๐ I write an article on web development and share valuable resources which might help you as a developer or beginner.
for more content
follow me ( Ganesh_Patil)
You can also connect with metwitter to get more content related to web development
Thank you for the support friends! ๐ฏ