透過遞迴構造字串 JavaScript
我們需要編寫一個遞迴函式,假設函式名稱為 pickString,該函式接受一個包含字母和數字組合的字串,並返回一個僅包含字母的新字串。
例如,
If the string is ‘dis122344as65t34er’, The output will be: ‘disaster’
因此,我們來編寫這個遞迴函式的程式碼 −
示例
const str = 'ex3454am65p43le';
const pickString = (str, len = 0, res = '') => {
if(len < str.length){
const char = parseInt(str[len], 10) ? '' : str[len];
return pickString(str, len+1, res+char);
};
return res;
};
console.log(pickString(str));
console.log(pickString('23123ca43n y43ou54 6do884 i43t'));
console.log(pickString('h432e54l43l65646o'));
console.log(pickString('t543h54is 54i5s 54t43he l543as53t
54ex87a455m54p45le'));輸出
控制檯中的輸出將為 −
example can you do it hello this is the last example
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP