这篇文章主要介绍了首字母大写的几种小技巧。

首字母大写js方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 方法1 (Vue 2.x 版本中使用过该方法)
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}

// 方法2 -- 使用replace
function capitalize(str) {
return str.replace(/^[a-z]/g, (L) => L.toUpperCase())
}

// 方法3
function capitalize(str) {
return str.replace(/^\S/g, (L) => L.toUpperCase())
}

// 方法3
function capitalize(str) {
return str.replace(/\b(\w)(\w*)/g, ($0, $1, $2) => {
return $1.toUpperCase() + $2
})
}

// 方法4 -- es6
function capitalize([c, ...r]) {
return c.toUpperCase() + r.join('')
}

首字母大写css方法

1
2
3
4
/* 方法5 -- 如果你只是想要单纯的在页面上展示一个首字母大写的字符串可以考虑使用css */
.capitalize {
text-transform: capitalize;
}