使多个高阶函数更简洁

Make multiple higher ordered functions more consice

我试图只将每个单词的第一个字母大写,同时删除 sentence.eg 开头和结尾的所有空格。

" a red carpet Is laid beFOre me " --> "A Red Carpet Is Laid Before Me"

我可以使用 regExp,但我不太熟悉它(非常欢迎提出建议)。我的做法是链接多个高阶函数,这对于给定的任务来说似乎太复杂了。我会喜欢任何其他方法来解决它。

//this function removes the whitespaces at the extreme ends of passed string

function removeOuterSpace(strArg) {
  return strArg.replace(/^\s*|\s*$/g, '')
}

// this function takes the actual string and does the rest

function firstUCase(str) {
  var newStr = (removeOuterSpace(str).split(' ')
    .map(function(items) {
      return items[0].toUpperCase() + items.slice(1, items.length)
    })).join(' ')
  return newStr
}

firstUCase(' the quIck brown fox jumps ')

编辑:结果是:"The QuIck Brown Fox Jumps"

你可以试试这个:

function firstUCase(str) {
  var newStr = (str.trim().split(' ')
    .map(function(items) {
      return items[0].toUpperCase() + items.slice(1, items.length).toLowerCase();
    })).join(' ')
  return newStr
}

firstUCase(' the quIck brown fox jumps ') //The Quick Brown Fox Jumps

firstUCase(' a red carpet Is laid beFOre me ') // A Red Carpet Is Laid Before Me

Javascript 已经有一个名为 .trim 的 built-in 函数(来自文档):

(...) removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

此外,您应该在切片部分的末尾添加 .toLowerCase() 以将字符串的其余部分小写。

或者,如果您想使用 regex,您可以尝试类似的操作:

function firstUCase(str) {
    return str
        .trim()
        .replace(/\b(\w)(\w*)/g, (word,letter,rest) => letter.toUpperCase() + rest.toLowerCase() )
}

firstUCase(' the quIck brown fox jumps ') //The Quick Brown Fox Jumps

firstUCase(' a red carpet Is laid beFOre me ') // A Red Carpet Is Laid Before Me

上面,.replace 方法接受一个函数作为第二个参数(文档 here) that can be used to replace the captured groups (first group = first letter, second group = rest of the sentence) with toUpperCase() and toLowerCase(), respectively. You can play with it here: http://regexr.com/3f4bg

使用 String.prototype.replace 函数的简短解决方案:

function firstUCase(str) {
  return str.trim().replace(/\b\w+\b/g, function (m) {
    return m[0].toUpperCase() + m.slice(1).toLowerCase();
  });
}
console.log(firstUCase(" a red carpet Is laid beFOre me  "));

确实有更简单的方法。首先,String.prototype.trim() 删除空格,然后正如您想象的那样,有一种方法可以使用正则表达式来简化过程:

function replacer(str){
    return str.toUpperCase();
}
function firstUCase(str) {
  var newStr = str.trim().toLowerCase();//remove spaces and get everything to lower case
  return newStr.replace(/\b\w/g, replacer);
}

console.log(firstUCase(' the quIck brown fox jumps '));

这是一个 regex-based 解决方案:

function replacer(match) {
  return match.charAt(0).toUpperCase() + match.slice(1);
}

function formatString(str) {
  return str
    .trim()
    .toLowerCase()
    .replace(/\b([a-z])/g, replacer);
}
  
console.log(formatString(" a red carpet Is laid beFOre me "));