
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Switch Positions of Selected Characters in a String in JavaScript
Problem
We are required to write a JavaScript function that takes in a string that contains only the letter ‘k’, ‘l’ and ‘m’.
The task of our function is to switch the positions of k with that of l leaving all the instances of m at their positions.
Example
Following is the code −
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));
Output
Following is the console output −
llklmkll
Advertisements