JS 字符串每个单词首字母大写的3种写法
提供三种写法
一、单个单词
var str1 = "abc"
str1 = str1.substr(0, 1).toUpperCase() + str1.substr(1,)
输出: Abc
三、多个单词
写法1:
str1 = "What doesn't kill you, Makes you stronger."
str1 = str1.split(" ")
var str2 = new Array()
for (let i=0;i < str1.length;i++){
str2[i] = str1[i].substr(0, 1).toUpperCase() + str1[i].substr(1,)
}
console.log(str2.join(" "))
写法2:
str1 = "What doesn't kill you, Makes you stronger."
str1 = str1.split(" ")
var str2 = new Array()
for (let i=0;i < str1.length;i++){
str2[i] = str1[i].charAt(0).toUpperCase() + str1[i].slice(1)
}
console.log(str2.join(" "))
写法3:ES6、ES7以上写法
str1 = "What doesn't kill you, Makes you stronger."
str1 = str1.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
以上输出结果: What Doesn't Kill You, Makes You Stronger.