javascript - 我如何构建这个新逻辑以适应预先存在的代码?
问题描述
我编写了一个代码,它从字符串中删除元音之前的所有辅音并将其替换为“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.
解决方案
我意识到这并不能真正回答您的问题,但是您现有的逻辑非常复杂,您可以使用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 - 从日期字符串以 UTC 正确计算日期时间
- unix - 从命令提示符执行相同的命令可以正常工作
- python - Defore 过采样数据显示 0
- python - 张量流中的花式索引
- javascript - 如何使用 require.js?
- django - Django - prefetch_related 的使用
- amazon-web-services - IOT 设备如何在设备预置期间使用预置声明证书与 AWS IOT 连接?
- express - 尝试使用邮递员更新我的 Express 数据库
- angular - 具有 RowCount 和 Results 作为单独字段的 Observable DataTable
- http - 什么字节范围 0- 表示