How to use Substring Replacement In Javascript
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.
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));
Output
hlleo
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