- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Regrouping characters of a string in JavaScript
- Finding count of special characters in a string in JavaScript
- Number of non-unique characters in a string in JavaScript
- Program to get final string after shifting characters with given number of positions in Python
- Replacing every nth instance of characters in a string - JavaScript
- Counting the number of redundant characters in a string - JavaScript
- How to find unique characters of a string in JavaScript?
- Generate random string/characters in JavaScript?
- Remove characters from a string contained in another string with JavaScript?
- Python program to validate string has few selected type of characters or not
- Formatting a string to separate identical characters in JavaScript
- Sorting string characters by frequency in JavaScript
- Placing same string characters apart in JavaScript
- Find numbers of balancing positions in string in C++
- Largest Substring Between Two Equal Characters in a string in JavaScript

Advertisements