惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
GbyAI
GbyAI
Jina AI
Jina AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 司徒正美
Hacker News - Newest:
Hacker News - Newest: "LLM"
V2EX - 技术
V2EX - 技术
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
F
Full Disclosure
S
Secure Thoughts
WordPress大学
WordPress大学
博客园 - Franky
N
News and Events Feed by Topic
雷峰网
雷峰网
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Hacker News: Front Page
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
TaoSecurity Blog
TaoSecurity Blog
C
CERT Recently Published Vulnerability Notes
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog
Security Latest
Security Latest
Attack and Defense Labs
Attack and Defense Labs
The Register - Security
The Register - Security
Spread Privacy
Spread Privacy
H
Help Net Security
宝玉的分享
宝玉的分享
L
LangChain Blog
MongoDB | Blog
MongoDB | Blog
I
Intezer
Schneier on Security
Schneier on Security
Latest news
Latest news
Y
Y Combinator Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
A
About on SuperTechFans
T
Tor Project blog
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
Microsoft Azure Blog
Microsoft Azure Blog
T
Threat Research - Cisco Blogs
S
Schneier on Security
Cisco Talos Blog
Cisco Talos Blog
H
Heimdal Security Blog

开飞机的老张

AGENTS.md Openspec 使用心得 从树莓派内网穿透到 Cloudflare Pages Openclaw和博客 郊眠寺 采石 译:我为什么使用Map(和WeakMap)处理DOM节点 介绍JavaScript中Symbol 原生JavaScript获取URL参数 用forEach()遍历对象 JavaScript禁用按钮 JavaScript的FormData JavaScript的Blob 用FileReader读取本地文件 JavaScript的Thenable JavaScript中Promise的reject JavaScript的立即调用函数表达式(IIFE) JavaScript的Promise链 用interact.js实现拖拽、缩放、吸附
字符串首字母大写
kaifeiji.cc · 2023-07-26 · via 开飞机的老张

原文:Capitalize the First Letter of a String in JavaScript

不用任何外部库,实现字符串首字母大写。

用字符串的toUpperCase()方法slice()方法可以轻松实现字符串的首字母大写。

1
2
3
4
const str = 'captain Picard';

const caps = str.charAt(0).toUpperCase() + str.slice(1);
caps;

首先将第一个字母转为大写,然后拼接剩余的字符。

如果要将字符串中的每一个单词首字母大写,可以用split()将字符串分割成单词,分别首字母大写后再用join()拼接成字符串,如下。

1
2
3
4
5
6
7
8
const str = 'captain picard';

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}

const caps = str.split(' ').map(capitalize).join(' ');
caps;

使用CSS

在前端,字符串的首字母大写并不需要JavaScript,CSS完全可以实现:

1
2
3
.capitalize {
text-transform: capitalize;
}

例如,以下<div>包含capitalize样式类,内部文本是captain picard,CSS可以将字符串中所有单词转为首字母大写。

1
<div class="capitalize">captain picard</div>

本教程对您有帮助吗?来GitHub仓库点个星支持我们吧!