如何编写一个函数,将句子中每个单词开头的所有辅音字符串都转换为“ r”,直到遇到元音为止?

时间:2018-07-21 00:20:27

标签: javascript user-defined-functions

史酷比挑战赛

  

您需要编写一个函数来替换所有辅音,   单词的开头,直到遇到带有“ r”的元音。对于   例如,单词“ scooby ”将变为“ rooby ”,而“ 木琴”将变为   成为“ 电话

这是我正在使用的功能,但仅对句子中的单个单词起作用。我怎样才能使它适用于每个单词。

function scooby_doo () {
    if (text.value.length == 0) {
        result.value = "no input given!";
    } else if (text.value.length > 0) {
        var set = text.value.split(" ");
        for (i = 0; i < set.length; i++) {
            result.value = set[i].replace (/^[^aeiou]+/i, "r");
        }
     } else {
        result.value = "";
    }
    return;
}

2 个答案:

答案 0 :(得分:4)

我相信您可以在没有显式循环的情况下实现:

str = 'scooby doo loves his xylophone show';
str.replace(/(^| |\n)[^aeiou]+/ig, '$1r');
// outputs "rooby roo roves ris rophone row"

这是您要寻找的输出吗?

答案 1 :(得分:2)

我认为您在代码中使用时会覆盖以前的值:

result.value = set[i].replace ( /^[^aeiou]+/i, "r" );

我不知道result的类型,但是您可以尝试以下解决方案:

function scooby_doo (text) {

var result = [];
if ( text.length == 0 )
{
    return 'no input given';
} else if ( text.length > 0 ) {
    var set = text.split ( " " );
    for ( i = 0; i < set.length; i++ ) {
        result.push(set[i].replace ( /^[^aeiou]+/i, "r" ));
    }
 } else {
    return '';
}

 return result.join(' ');
}

console.log('scooby xylophone')

"rooby rophone"