Switching 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 −

 Live Demo

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