How to use String Concatenation In Javascript
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.
// 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);
Output
lxampee
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