【问题标题】:Im writing a function that takes in a string and returns a string camelCased with the word ROD between each word instead of spaces我正在编写一个函数,该函数接受一个字符串并返回一个字符串 camelCased,每个单词之间带有单词 ROD 而不是空格
【发布时间】:2020-11-04 13:45:22
【问题描述】:

如何清理我的代码以不使用函数内部的函数?

function toRodCase(input) {
    if(!input) {
        return '';
    }

    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    function lowerCaseFirstLetter(string) {
        return string.charAt(0).toLowerCase() + string.slice(1);
    }
        
    let words = input.split(' ');
    for(let i = 0; i < words.length; i++){
        if(i === 0){
            words[i] = lowerCaseFirstLetter(words[i]);
        }else{
            words[i] = 'ROD' + capitalizeFirstLetter(words[i]);
        }
    }
    
    return words.join('');
}
 toRodCase("Hello there stealth warrior")

现在我在一个函数中有两个函数。我怎样才能减少这种情况或有更好的方法来做到这一点?

【问题讨论】:

  • 既然它们只用过一次,而且只是一个表达式……根本不让它们起作用?

标签: javascript loops for-loop if-statement


【解决方案1】:

考虑使用正则表达式。基于@christian-c-salvadó 对此处非常相似的用例的回答:Converting any string into camel case,您可以将函数缩短为以下内容:

function toRodCase(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, 'ROD');
}

这利用正则表达式首先进行必要的大写/小写更改,然后用您选择的分隔符替换每个空格。

您可以将其泛化为使用任何分隔符,如下所示:

function toSpacedCase(str, spacer) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, spacer);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多