使用 JavaScript 移動母音和子音
問題
我們需要編寫一個 JavaScript 函式,它接受一個英語字母的字串。我們的函式構建一個新字串,每個子音應透過字母表向前推進 9 個位置。如果經過“z”,則從“a”重新開始。每個母音應向前推進 5 個位置。
示例
以下程式碼 −
const str = 'sample string';
const moveWords = (str = '') => {
str = str.toLowerCase();
const legend = 'abcdefghijklmnopqrstuvwxyz';
const isVowel = char => 'aeiou'.includes(char);
const isAlpha = char => legend.includes(char);
let res = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(!isAlpha(el)){
res += el;
continue;
};
let pos;
const ind = legend.indexOf(el);
if(isVowel(el)){
pos = (21 + ind) % 26;
}else{
pos = (ind + 9) % 26;
};
res += legend[pos];
};
return res;
};
console.log(moveWords(str));輸出
bvvyuz bcadwp
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP