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

Updated on: 19-Apr-2021

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements