How to use Recursion In Javascript
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.
// 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);
Output
lpmaxee
JavaScript Program to Swap Characters in a String
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:
Table of Content
- Using Array Manipulation
- Using String Concatenation
- Using Regular Expressions
- Using Substring Replacement
- Using Recursion
Contact Us