Reversing a string in JavaScript involves creating a new string with the original string’s characters in the opposite order. This can be achieved by converting the string into an array, reversing the array, and then joining the array back into a string.
If you want to reverse string in javascript then use the reverse() method
var string = "Welcome to Javascript!";
console.log(string.split("").reverse().join(""));
Output:-
!tpircsavaJ ot emocleW
Reverse string without pre defined function
var string = "Welcome to Javascript!";
var arr= string.split("");
var i=0;
var new_arr=[];
for(i=arr.length-1; i>=0; i--){
new_arr.push(arr[i]);
}
console.log(new_arr.join(""));
Output:-
!tpircsavaJ ot emocleW
Reverse only string words
var string = "Welcome to Javascript!";
let data= string.split(" ");
let revdata=[];
for(let i=0; i<(data.length); i++)
{
revdata.push(data[i].split("").reverse().join(""));
}
console.log(revdata.join(" "));
Output:-
emocleW ot !tpircsavaJ
How to reverse string in Javascript? – Interview Questions
Q 1: How to reverse a string?
Ans: Convert to an array, reverse, and join.
Q 2: Can strings be reversed directly?
Ans: No, they are immutable.
Q 3: Method used to split the string?
Ans: split("").
Q 4: Method to reverse an array?
Ans: reverse().
Q 5: Method to join an array?
Ans: join("").
How to reverse string in Javascript? – Objective Questions (MCQs)
Q1. Which method splits a string into an array?
Q2. Which array method reverses elements?
Q3. Which method joins array elements into a string?
Q4. What is the output of: "abc".split("").reverse().join("")
Q5. Which data type is returned after reversing a string?