1 回答

TA貢獻1836條經驗 獲得超5個贊
您不需要將句子分成單個單詞,因為您對查看單詞不感興趣,而是對句子中的單個字符感興趣。考慮到這一點,您可以使用現有的當前循環,并為每個循環i從索引處的輸入句子中獲取當前字符i。
如果當前字符是元音(即:如果它包含在元音字符串中),則您知道當前字符是元音,因此,您可以將由 a 分隔的當前字符添加到輸出字符串中"b"。否則,如果它不是元音,您可以將當前字符添加到輸出字符串中。
請參閱下面的示例:
function abaTranslate(sentence) {
? const vowels = 'AEIOUaeiou';
? var newStr = "";
? for (var i = 0; i < sentence.length; i++) {
? ? var currentCharacter = sentence[i];
? ? if (vowels.includes(currentCharacter)) { // the current character is a vowel
? ? ? newStr += currentCharacter + "b" + currentCharacter;
? ? } else {
? ? ? newStr += currentCharacter; // just add the character if it is not a vowel
? ? }
? }
? return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
如果你想使用 JS 方法來幫助你實現這一點,你可以使用.replace()
正則表達式。盡管如此,在深入研究正則表達式之前,最好嘗試并理解上面的代碼:
const abaTranslate = sentence => sentence.replace(/[aeiou]/ig, "$&b$&");
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
添加回答
舉報