Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Switching positions of selected characters in a string in JavaScript
We are required to write a JavaScript function that takes in a string containing only the letters 'k', 'l' and 'm'. The task is to switch the positions of 'k' with 'l' while leaving all instances of 'm' at their original positions.
Problem Statement
Given a string with characters 'k', 'l', and 'm', we need to swap every occurrence of 'k' with 'l' and vice versa, keeping 'm' unchanged.
Example
Here's the implementation using a simple loop approach:
const str = 'kklkmlkk';
const switchPositions = (str = '') => {
let res = "";
for(let i = 0; i < str.length; i++){
if (str[i] === 'k') {
res += 'l';
} else if (str[i] === 'l') {
res += 'k';
} else {
res += str[i];
}
}
return res;
};
console.log(switchPositions(str));
llklmkll
Alternative Method Using replace()
We can also solve this using string replacement with a temporary placeholder:
const switchPositionsReplace = (str = '') => {
return str
.replace(/k/g, 'TEMP') // Replace k with temporary placeholder
.replace(/l/g, 'k') // Replace l with k
.replace(/TEMP/g, 'l'); // Replace temporary with l
};
const testStr = 'kklkmlkk';
console.log("Original:", testStr);
console.log("Switched:", switchPositionsReplace(testStr));
Original: kklkmlkk Switched: llklmkll
How It Works
The first method iterates through each character and builds a new string by replacing 'k' with 'l' and 'l' with 'k'. The second method uses regular expressions to perform global replacements with a temporary placeholder to avoid conflicts during the swap.
Conclusion
Both approaches effectively swap 'k' and 'l' characters while preserving 'm' positions. The loop method is more explicit, while the replace method is more concise for simple character swapping operations.
