2 回答

TA貢獻1788條經驗 獲得超4個贊
您當前嘗試的問題是以下代碼段:
while (true) {
if (!vowels.test(currentCharacter)) {
currentCharacter = str[currentIndex]
consonants += currentCharacter
currentIndex ++
} else {
break
}
}
這里有兩件事出了問題。
你
vowels
測試currentCharacter
. 如果currentCharacter
不是元音,則應將其直接添加到輸出中。您當前首先更改 的值,currentCharacter
然后再將其添加到輸出。您當前設置了一個新值
currentCharacter
before incrementingcurrentIndex
。這應該在之后完成。
讓我展開循環并演示問題:
/* str = "car"
* vowels = /[aeiou]/gi
* currentIndex = 0
* currentCharacter = "c"
* consonants = ""
*/
if (!vowels.test(currentCharacter)) //=> true
currentCharacter = str[currentIndex];
/* currentIndex = 0
* currentCharacter = "c"
* consonants = ""
*/
consonants += currentCharacter
/* currentIndex = 0
* currentCharacter = "c"
* consonants = "c"
*/
currentIndex ++
/* currentIndex = 1
* currentCharacter = "c"
* consonants = "c"
*/
if (!vowels.test(currentCharacter)) //=> true
currentCharacter = str[currentIndex];
/* currentIndex = 1
* currentCharacter = "a"
* consonants = "c"
*/
consonants += currentCharacter
/* currentIndex = 1
* currentCharacter = "a"
* consonants = "ca"
*/
currentIndex ++
/* currentIndex = 2
* currentCharacter = "a"
* consonants = "ca"
*/
if (!vowels.test(currentCharacter)) //=> false
要解決此問題,您只需移動 的賦值currentCharacter并將其放在 的增量之后currentIndex。
while (true) {
if (!vowels.test(currentCharacter)) {
consonants += currentCharacter
currentIndex ++
currentCharacter = str[currentIndex] // <- moved two lines down
} else {
break
}
}
function solution(str) {
let vowels = /[aeiou]/gi
let currentIndex = 0
let currentCharacter = str[currentIndex ]
let consonants = ''
let outputStr = ''
if (vowels.test(currentCharacter)) {
outputStr = currentCharacter
} else {
while (true) {
if (!vowels.test(currentCharacter)) {
consonants += currentCharacter
currentIndex ++
currentCharacter = str[currentIndex]
} else {
break
}
}
outputStr = `${consonants}`
}
return outputStr
}
console.log(solution('glove'))

TA貢獻1860條經驗 獲得超9個贊
您可以使用以錨點開頭的交替^
來匹配斷言[aeiou]
右側輔音的元音,或者匹配 1 個或多個輔音的其他方式。
\b(?:[aeiou](?=[b-df-hj-np-tv-z])|[b-df-hj-np-tv-z]+(?=[aeiou]))
function solution(str) {
const regex = /^(?:[aeiou](?=[b-df-hj-np-tv-z])|[b-df-hj-np-tv-z]+(?=[aeiou]))/i;
let m = str.match(regex);
return m ? m[0] : str;
}
console.log(solution('egg'));
console.log(solution('car'));
console.log(solution('glove'));
添加回答
舉報