JavaScript Reverse a string in place
Last Updated :
17 Jun, 2024
JavaScript reverses a string in place refers to the process of flipping the order of characters within the string without using additional memory. It involves iterating through the string and swapping characters from both ends until reaching the middle.
Reverse a string in place Example
Using the JavaScript split() method
JavaScript String split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Example: This example reverses the string by first splitting it with ("") separator and then reversing it and finally joining it with ("") separator.
JavaScript
let str = "This is GeeksForGeeks";
console.log("Input string is : " + str);
function gfg_Run() {
console.log(
"Reverse String" +
str.split("").reverse().join("")
);
}
gfg_Run();
OutputInput string is : This is GeeksForGeeks
Reverse StringskeeGroFskeeG si sihT
Using the Array reverse() method
JavaScript Array.reverse() Method is used for the in-place reversal of the array. The first element of the array becomes the last element and vice versa.
Example: This example uses the concept of the merge sort algorithm.
JavaScript
// Input sting
let str = "This is GeeksForGeeks";
console.log("Input string is : " + str);
// Function to reverse string
function reverse(s) {
if (s.length < 2) return s;
let hIndex = Math.ceil(s.length / 2);
return (
reverse(s.substr(hIndex)) +
reverse(s.substr(0, hIndex))
);
}
// Function to display output
function gfg_Run() {
console.log(reverse(str));
}
// Function call
gfg_Run();
OutputInput string is : This is GeeksForGeeks
skeeGroFskeeG si sihT
Using the Array join() method
The JavaScript Array join() Method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).
Example: This example takes a variable and appends the result from the end of the string.
JavaScript
// Input sting
let str = "A Computer Science Portal";
console.log("Input string is : " + str);
// Function to reverse string
function reverse(s) {
// Variable to store reverse
let o = "";
for (let i = s.length - 1; i >= 0; o += s[i--]) {}
return o;
}
// Function to display output
function gfg_Run() {
console.log(reverse(str));
}
// Function call
gfg_Run();
OutputInput string is : A Computer Science Portal
latroP ecneicS retupmoC A
Using substr() method
JavaScript str.substr() method returns the specified number of characters from the specified index from the given string. It basically extracts a part of the original string.
Example: This example uses str.substr() method to reverse a string.
JavaScript
// Input sting
let str = "This is GeeksForGeeks";
console.log("Input string is : " + str);
// Function to reverse string
function reverse(s) {
if (s.length < 2) return s;
let hIndex = Math.ceil(s.length / 2);
return (
reverse(s.substr(hIndex)) +
reverse(s.substr(0, hIndex))
);
}
// Function to display output
function gfg_Run() {
console.log(reverse(str));
}
// Function call
gfg_Run();
OutputInput string is : This is GeeksForGeeks
skeeGroFskeeG si sihT
Using for loop
To reverse a string in place using a for loop in JavaScript, iterate over half the string length, swapping characters from both ends until reaching the middle. Return the modified string.
Example: In this example the function iterates backward through the string, appending each character to a new string, effectively reversing it. Then, it returns the reversed string.
JavaScript
// reverse string using for loop
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
let str = 'This is GeekForGeeks';
console.log("Original string is: ",str);
console.log("Reversed string is: ",reverseString(str));
OutputOriginal string is: This is GeekForGeeks
Reversed string is: skeeGroFkeeG si sihT
Using the Array reduce() method
JavaScript Array reduce() method executes a reducer function on each element of the array, resulting in a single output value. It can be utilized to reverse a string by iterating over each character and prepending it to an accumulator string.
Example:
JavaScript
// Input sting
let str = "This is GeeksForGeeks";
console.log("Input string is : " + str);
// Function to reverse string
function reverse(s) {
return s.split("").reduce((acc, char) => char + acc, "");
}
// Function to display output
function gfg_Run() {
console.log(reverse(str));
}
// Function call
gfg_Run();
OutputInput string is : This is GeeksForGeeks
skeeGroFskeeG si sihT
Using Two-Pointer Technique
The two-pointer technique involves using two pointers, one starting from the beginning of the string and the other from the end. By swapping the characters at these pointers and moving the pointers towards each other until they meet in the middle, we can reverse the string in place.
Example:
This example demonstrates how to reverse a string using the two-pointer technique.
JavaScript
// Function to reverse string in place using two-pointer technique
function reverseStringInPlace(str) {
// Convert string to array to mutate it
let charArray = str.split('');
let left = 0;
let right = charArray.length - 1;
// Swap characters until the pointers meet in the middle
while (left < right) {
// Swap characters at left and right pointers
[charArray[left], charArray[right]] = [charArray[right], charArray[left]];
// Move the pointers towards the middle
left++;
right--;
}
// Convert array back to string
return charArray.join('');
}
// Example usage
let str = "This is GeeksForGeeks";
console.log("Original string is: ", str);
console.log("Reversed string is: ", reverseStringInPlace(str));
OutputOriginal string is: This is GeeksForGeeks
Reversed string is: skeeGroFskeeG si sihT
Similar Reads
Reverse a String in JavaScript We have given an input string and the task is to reverse the input string in JavaScript. Reverse a String in JavaScriptUsing split(), reverse() and join() MethodsThe split() method divides the string into an array of characters, reverse() reverses the array, and join() combines the reversed characte
1 min read
Perfect Reversible String in JavaScript A string is said to be a perfectly reversible string when the reverse of all the possible substrings of the string is available or present in the string. In this article, we are going to check whether a string is a perfectly reversible string or not in JavaScript with the help of practical implement
5 min read
Javascript Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
PHP Reverse a String Reversing a string in PHP refers to rearranging a given string's characters in reverse order, starting from the last character to the first. This task is often used in text manipulation or algorithm challenges, highlighting PHP's string-handling capabilities.Examples: Input : GeeksforGeeksOutput : s
3 min read
JavaScript Array reverse() Method The JavaScript Array reverse() method reverses the order of the elements in an array in place. The first array element becomes the last, and the last element becomes the first, and so on.It modifies the original array and returns a reference to the reversed array. We can also use the Array.toReverse
3 min read
Reverse Only the Odd Length Words using JavaScript Given a string containing words separated by spaces, our task is to reverse only the words with an odd length. The rest of the words remain unchanged. Example: Input: Hellow world how are you? Output: Hellow dlrow woh era you?Below are the approaches to Reverse only the odd-length words: Table of Co
3 min read
Reverse a String in TypeScript Reversing a string involves changing the order of its characters, so the last character becomes the first, and vice versa. In TypeScript, there are various methods to achieve this, depending on the developer's preference and the specific requirements of the task. Table of Content Using a LoopUsing A
2 min read
Javascript Program to Modify a string by performing given shift operations Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task i
3 min read
p5.js reverse() function The reverse() function in p5.js is used to reverse the order of the given array element. Syntax: reverse(Array) Parameters: This function accepts a parameter Array whose elements are to be reversed. Return Value: It returns a new reversed array. Below program illustrates the reverse() function in p5
1 min read
JavaScript Program to Reverse Digits of a Number Reversing the digits of a number means rearranging its digits in the opposite order. For instance, reversing 1234 gives 4321. In JavaScript, this is typically achieved by converting the number to a string, reversing the characters, and converting it back to a number, offering efficient manipulation.
3 min read