javascript - 让多个高阶函数更加简洁

标签 javascript arrays regex string higher-order-functions

我试图仅将每个单词的第一个字母大写,同时删除句子开头和结尾处的任何空格。例如。

" 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 的内置函数(来自文档):

(...) 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() 以小写字符串的其余部分。

或者,如果您想使用正则表达式,您可以尝试类似的操作:

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 方法接受一个函数作为第二个参数(docs here ),可用于替换捕获的组(第一个组 = 第一个字母,第二个组 = 句子的其余部分) ) 分别使用 toUpperCase()toLowerCase()。你可以在这里玩它:http://regexr.com/3f4bg

关于javascript - 让多个高阶函数更加简洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41794787/

相关文章:

php - 如何在foreach循环中从数组中删除重复值?

CUDA 将充满数据的数组从主机复制到设备

java - 正则表达式解析可能由或不由 ; 分隔的字符串分成几组

javascript - 使用 RegEx trim 文件名

javascript - 如何使用 PHP 打开 Bootstrap 模式?

javascript - 如何让 JS 工具提示在 Shadow DOM 中工作?

javascript - 使用颜色选择器手动更改单元格/行/列的颜色?

javascript - 如何提取数组的偶数元素?

c# - 一维数组等价于多维数组?

java - 如何使用 Java 从 html 中删除特定标签?