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

首字母大写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(/\b(\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;
}
posted @ 2020-08-19 22:15  小方块的世界  阅读(814)  评论(0编辑  收藏  举报