我试图仅将每个单词的第一个字母大写,同时删除句子开头和结尾处的任何空格。例如。
" 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/