Interview Questions- Part-9

Reverse string -- split , reverse and join

				
					let name = "anurag";
console.log(name.split("").reverse().join(""));
				
			

Reverse string -- using spread operator, reverse , join

				
					let name = "anurag";
console.log([...name].reverse().join(""));

				
			

Reverse string using forloop

				
					let name = "anurag";
for (let i = name.length - 1; i >= 0; i--) {
  finalname += name[i];
}
console.log(finalname);
				
			

Reverse using charAt

				
					let name = "anurag";
let length = name.length - 1;
let finalname = "";
while (length >= 0) {
  finalname += name.charAt(length);
  length--;
}
console.log(finalname);
				
			

Reverse string using substr and slice

				
					let name = "anurag";
let length = name.length - 1;
let finalname = "";
while (length >= 0) {
  finalname += name.substr(length);
  name = name.slice(0, -1);
  length--;
}
console.log(finalname);
				
			

Reverse string using recursion

				
					const reverseString = (str) => {
  return str === "" ? "" : reverseString(str.substr(1)) + str.charAt(0);
};
let x = reverseString("anurag");
console.log(x);

				
			

Leave a Comment