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'));
添加回答
举报