DSA Q-4

3 min readJan 16, 2024

reverse string by multiple ways

01.using split ,reverse and join:

function reverseStr ( str ) {
return str.split(" ").reverse().join(" ")
}
const reverseString = (" hello, lala")
console.log(reverseString)
// output :" lala,olleh"

explaination:

split method convert string into array with splitting element of an array and reverse method reverse as it is splited array element and join method joins the reversed array of characters back into a string.

02.for loop

function reverseStr(str){
let reversed='' '';
for(let i=str.length-1;i≥0;i- -){
reversed+=str[i]
}
return reversed;
}
const myString=reverseStr('hello , lala");
console.log(myString);// output:('lala olleh')

Explaination:

in for lop each character iterate from the last to the first .and concate each character in the reversed string

03.Array reduce method

function reverseStr(str){
return str.split(' ').reduce((a,b)=>b+a, " ")
}
const reversedString = reverseString('Hello, World!');
console.log(reversedString); // Outputs: '!dlroW ,olleH'

Explaination:

split method Split the string into an array of characters.and reduce method used to Accumulate characters by prefixing each character to the current reverse string.

04. by Recursion function;

The function calls itself recursively, reversing the substring excluding the first character and then appending the first character.

function reverseString(str) {
if (str === ' ') {
return str;
} else {
return reverseString(str.substr(1)) + str[0];
}
}
const reverseStr=reverseString("hello lala");
console.log(reverseStr);
output=>lala olleh

Explaination :

Base Case:

  • if (str === ' '): This is the base case of the recursion. It checks if the input string str is an empty string. If it is, the function returns the empty string itself. This is the stopping condition for the recursion.

Recursive Case:

  • else: If the input string is not empty, the function enters the else block.
  • return reverseString(str.substr(1)) + str[0];: This line is the recursive step.
  • str.substr(1): This extracts a substring of str starting from the second character (index 1) until the end of the string. It effectively removes the first character.
  • reverseString(...): The function calls itself with the shortened substring.
  • + str[0]: It then adds the first character of the original string to the result of the recursive call. This effectively builds the reversed string one character at a time.

Example:

Let’s say you call reverseString('hello'):

  1. First call: reverseString('hello')
  • Calls reverseString('ello') + 'h'
  1. Second call: reverseString('ello')
  • Calls reverseString('llo') + 'e'
  1. Third call: reverseString('llo')
  • Calls reverseString('lo') + 'l'
  1. Fourth call: reverseString('lo')
  • Calls reverseString('o') + 'l'
  1. Fifth call: reverseString('o')
  • Calls reverseString('') + 'o'

Base case is reached.

Now, the recursion starts to unwind:

  1. 'o' + 'l': 'ol'
  2. 'lo' + 'l': 'lol'
  3. 'llo' + 'e': 'lloe'
  4. 'ello' + 'h': 'elloh'
  5. 'hello' is the final reversed string.

So, the function effectively reverses the input string using recursion and concatenation.

05.Array.from

function reverseStr(str){
return array.from(str).reverse().join("")
}
const reverseString=reverseStr("hello lala")
console.log(reverseString)
output:olleh lala

explaination:

here array.from method creat array from string

06. spread operator

const reverseString = (str) => {
return [...str].reverse().join('');
};

// Example usage:
console.log(reverseString("hello")); // Output: "olleh"

Explanation:

  • [...str]: Uses the spread operator to create an array from the string.

7. Using Recursive Approach (ES6):

ES6 arrow function with ternary operator.

const reverseString =str=> str===" " ?str :reverseString(str.substr(1)+str[0];
const reversedString=reverseString('hello, lala')
console.log(reversedString)// lala olleh;

08 .Using Map Function:

function reverseStr(str){
return array.prototype.map.call(str, char =>char).reverse().join(" ");
array.prototype.map.call(str, char =>char) maps each charachter to an array
join(''): Joins the reversed array back into a string.

9. Using ReduceRight:

reduceRight(): Similar to reduce() but processes the array from right to left.

function reverseString(str) {
return Array.from(str).reduceRight((reversed, char) => reversed + char, '');
}
const reversedString = reverseString('Hello, World!');
console.log(reversedString);
// Outputs: '!dlroW ,olleH'

10 .using do while loop

function reverseString(str) {
let reversed = '';
let i = str.length - 1;
while (i >= 0) {
reversed += str[i];
i - ;
}
return reversed;
}
const reversedString = reverseString('Hello, World!');
console.log(reversedString); // Outputs: '!dlroW ,olleH'

Traditional while loop to iterate over characters in reverse order.

--

--

PROFESSOR !!
PROFESSOR !!

Written by PROFESSOR !!

start the journey with me and be a master in js and react to beacome a frontend developer

No responses yet