我编写了一个代码,从字符串中删除元音之前的所有辅音,并将其替换为“r”,在这种情况下,字符串以元音开头,它应该返回单词而不对其进行任何操作。现在,我想添加我想到的两件事,但不幸的是,我无法做到: 1. 当输入的字符串都是辅音时,它不应该执行任何操作,只返回字符串。 2. 如果用户在空格中键入“”,则应将其 trim 。 如何将此逻辑放入下面的代码中而不影响已经运行的内容?
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.
最佳答案
我意识到这并不能真正回答你的问题,但你现有的逻辑非常复杂,你可以使用 String.trim
、.toLowerCase
和.replace
:
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') + '*')
**
正则表达式使用正向前视来确保字符串中存在元音,如果存在,则用 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');
}
关于javascript - 如何构造这个新逻辑以适应预先存在的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125628/