2 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
您當(dāng)前嘗試的問題是以下代碼段:
while (true) {
if (!vowels.test(currentCharacter)) {
currentCharacter = str[currentIndex]
consonants += currentCharacter
currentIndex ++
} else {
break
}
}
這里有兩件事出了問題。
你
vowels
測(cè)試currentCharacter
. 如果currentCharacter
不是元音,則應(yīng)將其直接添加到輸出中。您當(dāng)前首先更改 的值,currentCharacter
然后再將其添加到輸出。您當(dāng)前設(shè)置了一個(gè)新值
currentCharacter
before incrementingcurrentIndex
。這應(yīng)該在之后完成。
讓我展開循環(huán)并演示問題:
/* 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
要解決此問題,您只需移動(dòng) 的賦值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貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用以錨點(diǎn)開頭的交替^
來(lái)匹配斷言[aeiou]
右側(cè)輔音的元音,或者匹配 1 個(gè)或多個(gè)輔音的其他方式。
\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'));
添加回答
舉報(bào)