How to use Array Manipulation In Javascript
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.
// 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);
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
Contact Us