JavaScript Program to Swap Characters in a String
Last Updated :
17 Jun, 2024
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently.
There are different approaches for swapping characters in a String in JavaScript:
Using Array Manipulation
In this approach, we convert the input string into an array of characters, perform the character swap using array manipulation techniques, and then convert the array back into a string.
- Convert the String to an Array: We begin by splitting the input string into an array of individual characters. This allows us to directly access and modify characters using array indexing.
- Swap Characters: Using array destructuring, we swap the characters at the desired positions in the array. This approach is concise and readable.
- Convert Back to String: After swapping the characters in the array, we use the join() method to convert the modified array back into a string.
Example: Define a function to swap characters in a string using array manipulation.
JavaScript
// Define a function to swap characters in a
// string using array manipulation
function swapCharacters(inputString, index1, index2) {
// Convert the input string into an array of characters
let charArray = inputString.split('');
// Swap the characters at the specified indices
// using array destructuring
[charArray[index1], charArray[index2]] =
[charArray[index2], charArray[index1]];
// Join the array back into a string
// and return the result
return charArray.join('');
}
// Original string
const originalString = "example";
// Swap characters at index 0 and 5
const swappedString =
swapCharacters(originalString, 0, 5);
// Output the swapped string
console.log(swappedString);
Using String Concatenation
This approach involves breaking down the original string into substrings, rearranging them, and then concatenating them to create the swapped string.
- Extract Substrings: We use the substring() method to extract three substrings: before the first character to swap, between the two characters to swap, and after the second character to swap.
- Construct Swapped String: By rearranging these substrings and inserting the characters to swap in the desired positions, we construct the swapped string.
Example: Define a function to swap characters in a string using string concatenation.
JavaScript
// Define a function to swap characters in
// a string using string concatenation
function swapCharactersConcat(inputString, index1, index2) {
// Extract characters at the specified indices
const charAtIndex1 = inputString[index1];
const charAtIndex2 = inputString[index2];
// Create a new string with characters swapped
const swappedString = inputString.substring(0, index1) +
charAtIndex2 +
inputString.substring(index1 + 1, index2) +
charAtIndex1 +
inputString.substring(index2 + 1);
// Return the swapped string
return swappedString;
}
// Original string
const originalString = "example";
// Swap characters at index 0 and 5
const swappedString =
swapCharactersConcat(originalString, 0, 5);
// Output the swapped string
console.log(swappedString);
Using Regular Expressions
Using regular expressions, we can capture the characters to be swapped and rearrange them accordingly, resulting in the desired swapped string.
- Create a Pattern: We define a regular expression pattern that captures groups of characters, including those before and after the characters to swap.
- Create a Replacement Pattern: A replacement pattern is crafted to rearrange the captured groups, effectively swapping the characters in the string.
- Apply the Regular Expression: We use the replace() method with the regular expression and the replacement pattern to perform the character swap.
Example: Define a function to swap characters in a string using regular expressions
JavaScript
// Define a function to swap characters in a
// string using regular expressions
function swapCharactersRegex(inputString, index1, index2) {
// Create a pattern that captures substrings
// before, between, and after the indices
const pattern =
`(.{${index1}})(.)(.{${index2 - index1 - 1}})(.)(.*)`;
// Create a replacement pattern that reorders
// the captured groups
const replacement = `$1$4$3$2$5`;
// Use the regular expression to replace the
// captured substrings and swap the characters
const swappedString =
inputString.replace(new RegExp(pattern), replacement);
// Return the swapped string
return swappedString;
}
// Original string
const originalString = "example";
// Swap characters at index 0 and 5
const swappedString =
swapCharactersRegex(originalString, 0, 5);
// Output the swapped string
console.log(swappedString);
Using Substring Replacement
This approach extracts substrings before and after the specified positions, swaps them with the characters at those positions, and concatenates them with the swapped characters in the middle, effectively swapping the characters in the string.
Example: The function swapCharsSubstringReplacement swaps characters at positions i and j in the string str using substring replacement and returns the modified string.
JavaScript
function swapCharsSubstringReplacement(str, i, j) {
return str.substring(0, i) + str[j] + str.substring(i + 1, j) + str[i] +
str.substring(j + 1);
}
console.log(swapCharsSubstringReplacement("hello", 1, 3));
Using Recursion
This approach utilizes the recursive function to swap characters in a string. It leverages the idea of breaking the problem down into smaller subproblems, each involving a string with characters at specific indices swapped.
Recursive Strategy:
- Base Case: If the string length is 1 or 0, return the string as it is.
- Swap Characters: Swap characters at the given indices.
- Recursive Call: Recursively call the function on the remaining part of the string.
Example: Define a function to swap characters in a string using recursion.
JavaScript
// Define a function to swap characters in a string using recursion
function swapCharactersRecursive(inputString, index1, index2) {
if (index1 >= index2) {
return inputString;
}
// Swap characters at index1 and index2
inputString = inputString.substring(0, index1) + inputString[index2] +
inputString.substring(index1 + 1, index2) + inputString[index1] +
inputString.substring(index2 + 1);
// Recursive call with indices moved towards each other
return swapCharactersRecursive(inputString, index1 + 1, index2 - 1);
}
// Original string
const originalString = "example";
// Swap characters at index 0 and 5
const swappedString = swapCharactersRecursive(originalString, 0, 5);
// Output the swapped string
console.log(swappedString);
Using Temporary Variable
This approach involves using a temporary variable to store one of the characters while swapping. This is a classic method used in various programming languages and can be easily implemented in JavaScript.
Example: Define a function to swap characters in a string using a temporary variable.
JavaScript
// Define a function to swap characters in a string using a temporary variable
function swapCharactersTemp(inputString, index1, index2) {
// Convert the input string into an array of characters
let charArray = inputString.split('');
// Use a temporary variable to swap the characters
let temp = charArray[index1];
charArray[index1] = charArray[index2];
charArray[index2] = temp;
// Join the array back into a string and return the result
return charArray.join('');
}
// Original string
const originalString = "example";
// Swap characters at index 0 and 5
const swappedString = swapCharactersTemp(originalString, 0, 5);
// Output the swapped string
console.log(swappedString);
Similar Reads
JavaScript Program to Mirror Characters of a String
Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to
6 min read
JavaScript Program to Access Individual Characters in a String
In this article, we are going to learn about accessing individual characters from the given string. Accessing individual characters in a string means retrieving a specific character from the string using its index position (zero-based) or iterating through each character one by one. Example: Input :
4 min read
JavaScript - How to Replace Multiple Characters in a String?
Here are the various methods to replace multiple characters in a string in JavaScript.1. Using replace() Method with Regular ExpressionThe replace() method with a regular expression is a simple and efficient way to replace multiple characters.JavaScriptconst s1 = "hello world!"; const s2 = s1.replac
3 min read
JavaScript Program to FindNumber of Flips to make Binary String Alternate
In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern.Examples:Inp
4 min read
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elementsâ positions and printing the output in the console.Examples:Input: helloOutput: lelhoExplanation: h,l,l are consonants in the given str
6 min read
Java Program to Add Characters to a String
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
4 min read
JavaScript - Characterrs to Opposite Case in a String
Here are the various approaches to convert each character of a string to its opposite case (uppercase to lowercase and vice versa).Using for Loop and if-else Condition - Most CommonIn this approach, we iterate through each character of the string. Using an if-else statement, it checks if each charac
3 min read
Java Program to Replace Multiple Characters in a String
In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
3 min read
Convert a String to a List of Characters in Java
In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
3 min read
Java Program to Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII v
5 min read