我编写了一个代码,它从字符串中删除元音之前的所有辅音并用'r'替换它,在这种情况下,字符串以元音开头,它应该返回该字而不对其做任何事情。现在,我想添加两件我想到的东西但不幸的是,我无法: 1.当字符串输入都是辅音时,它应该什么也不做,只返回字符串。 2.如果用户在空间中输入''那么它应该被修剪掉。 如何将此逻辑放在下面的代码中而不影响已经工作的内容?
const scoobyDoo = str => {
if(typeof str !== 'string'){
return 'This function accepts strings only';
}
let newStr = str.toLowerCase().split('');
let arrWord = newStr.length;
let regex = /[aeiou]/gi;
if (newStr[0].match(regex)){
let nothing = newStr.join('');
return nothing;
}
else {
for (let i = 0; i < arrWord; i++){
let vowelIndex = newStr.indexOf(str.match(regex)[i].toLowerCase());
newStr.splice(0, vowelIndex, 'r');
return newStr.join('');
}
}
}
console.log(scoobyDoo('scooby'));//works as expected returns 'rooby'
console.log(scoobyDoo('ethane'));//works as expected returns 'ethane'
console.log(scoobyDoo('why'));// should return 'why'
console.log(scoobyDoo(' '));// should return trimmed space and a
text telling the user only spaces were entered.
答案 0 :(得分:1)
我意识到这并没有真正回答你的问题,但你现有的逻辑非常复杂,你可以通过String.trim
,.toLowerCase
和.replace
获得相同的结果:< / p>
console.log('scooby'.trim().toLowerCase().replace(/^(?=.*?[aeiou])[^aeiou]+/, 'r'))
rooby
console.log('ethane'.trim().toLowerCase().replace(/^(?=.*?[aeiou])[^aeiou]+/, 'r'))
ethane
console.log('why'.trim().toLowerCase().replace(/^(?=.*?[aeiou])[^aeiou]+/, 'r'))
why
console.log('*' + ' '.trim().toLowerCase().replace(/^(?=.*?[aeiou])[^aeiou]+/, 'r') + '*')
**
regexp使用正向前瞻来确保字符串中有元音,如果是,则用r替换所有前导辅音。
要根据现有功能执行更多操作,您可以尝试这样做。它仍然广泛使用正则表达式函数。
const scoobyDoo = str => {
if(typeof str !== 'string'){
return 'This function accepts strings only';
}
// is it a blank string?
if (str.match(/^\s+$/)) {
return '';
}
// does it start with a vowel? if so, nothing to do
if (str.match(/^[aeiou]/i)) {
return str;
}
// does it only contain consonants?
if (!str.match(/[aeiou]/i)) {
return str;
}
// must not start with a vowel but still include one
return str.replace(/^[^aeiou]+/i, 'r');
}