By Hemanta Sundaray on 2021-07-13
const reversed = str => {
return str.split("").reverse().join("")
}
console.log(reversed("hemanta"))
// atnameh
split()
split(separator)
The split() method returns an array of strings, split at each point where the separator occurs in the given string. If the separator is an empty string (" "), str is converted to an array of its characters.
The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first. The reverse() method changes the original array.
const person = ["hemanta", "kumar", "sundaray"]
console.log(person.reverse())
// ["sundaray", "kumar", "hemanta"]
The join() method creates and returns a new string by concatentaing all of the elements in an array, separated by a specified separator string.
If the separator is an empty string, all elements are joined without any characters in between them.
Using for loop:
const reversed = str => {
let reversedString = " "
for (let i = str.length - 1; i >= 0; i--) {
reversedString += str[i]
}
return reversedString
}
console.log(reversed("hemanta"))
// atnameh
Using the JavaScript reducer method:
const reversed = str => {
const strArray = str.split("")
return strArray.reduce(
(accumulator, currentCharacter) => currentCharacter + accumulator,
" "
)
}
console.log(reversed("hemanta"))
// atnameh