以字母順序從 JavaScript 中的字串中移除 n 個字元
問題
我們需要編寫一個 JavaScript 函式,該函式輸入一個字母小寫字串和數字 num。
我們的函式應按照字母順序從陣列中移除 num 個字元。這意味著我們應先移除 a(如果存在),然後依次移除 b、c,依此類推,直至達到所需的 num。
示例
程式碼如下 −
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));輸出
控制檯輸出如下 −
sus
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP