字符串首字母大写的小技巧

首字母大写js方法

// 方法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(/(w)(w*)/g, ($0, $1, $2) => {
        return $1.toUpperCase() + $2
    })
}

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

首字母大写css方法

/* 方法5 -- 如果你只是想要单纯的在页面上展示一个首字母大写的字符串可以考虑使用css */
.capitalize {
    text-transform: capitalize;
}
原文地址:https://www.cnblogs.com/codebook/p/13532273.html