javascript string reverse code example
Example 1: javascript reverse a string
function reverseString(s){
return s.split("").reverse().join("");
}
reverseString("Hello");//"olleH"
Example 2: javascrip reverse text
//more compact way:
"my example text".split("").reverse().join("");
Example 3: javascript string reverse
"this is a test string".split("").reverse().join("");
//"gnirts tset a si siht"
// Or
const reverse = str => [...str].reverse().join('');
// Or
const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, '');
// Or
const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`;
// Example
reverse('hello world'); // 'dlrow olleh'
Example 4: reverse a string javascript
//with built-in method
let string = "We are going to reverse a string with built-in method.";
let reversed = string.split("").reverse().join("");
console.log(reversed);
//with the for loop
let string = "We are going to reverse a string with the for loop.";
function reverse (string){
let reversed = "";
for(let char of string){
reversed = char + reversed;
}
return reversed;
}
console.log(reverse(string));
//with the spread operator
let string = "We are going to reverse a string with the spread operator.";
let reversed = [...string].reverse().join("");
console.log(reversed);
//with iteration
let string = "We are going to reverse a string with iteration.";
function reverse(string) {
for (var reversed = "", i = string.length - 1; i >= 0; i--) {
reversed += string[i];
}
return reversed;
console.log(reverse(string));
Example 5: reverse string js
const solution = (str) => str.split("").reverse().join("");
Example 6: reverse string javascript
// hey buddy, here are different implementations, choose your favourite !!
// best implementation
const reverse = (str) => str.split("").reverse().join("");
// explanation
function reverse1(str) {
// turn string to array, each char of the string will be part of the
// array as an individual element
const arr = str.split("");
// swap all the indexes of the array
arr.reverse();
// join every element back together
const res = arr.join("");
return res;
}
// without using REVERSE method
// recursive function
function reverse2(str) {
let res = "";
for (let i = 0; i < str.length; i++) res = str[i] + res;
return res;
}
// using REDUCE ( high order array function )
function reverse3(str) {
return str.split("").reduce((output, char) => {
return char + output;
}, "");
}