javascript - 如何构造这个新逻辑以适应预先存在的代码?

标签 javascript

我编写了一个代码,从字符串中删除元音之前的所有辅音,并将其替换为“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/

相关文章:

函数中的 JavaScript 变量

javascript - 如何在 HTML/Javascript 中循环更改文本?

javascript - WebdriverIO browser.click 给出错误 "Other element would receive the click"。我该如何解决?

javascript - 不使用 id 或 class 获取 DOM 元素

javascript - 单击 javascript 上的下拉菜单时如何执行函数调用

javascript - 不明白这里发生了什么;带有 jQ​​uery 对象的匿名函数

Javascript 通过引用传递变量

javascript - GWT:将文本设置在标签的中间(垂直)

javascript - 设置值后Codemirror自动格式化

javascript - 刷新 iframe 而不刷新整个页面