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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Introduction to Tree Data Structure Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or
15+ min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read