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
Selected Reading
Removing n characters from a string in alphabetical order in JavaScript
Problem
We are required to write a JavaScript function that takes in a lowercase alphabet string and number num.
Our function should remove num characters from the array in alphabetical order. It means we should first remove ‘a’ if they exist then ‘b’ , ‘c’ and so on until we hit the desired num.
Example
Following is the code −
const str = 'abascus';
const num = 4;
const removeAlphabetically = (str = '', num = '') => {
const legend = "abcdefghijklmnopqrstuvwxyz";
for(let i = 0; i < legend.length; i+=1){
while(str.includes(legend[i]) && num > 0){
str = str.replace(legend[i], "");
num -= 1;
};
};
return str;
};
console.log(removeAlphabetically(str, num));
Output
Following is the console output −
sus
Advertisements
