实现js字符串首字母大写的方法

分类:知识百科 日期: 点击:0

js字符串首字母大写的实现方法有很多,其中最常用的方法有以下几种:

1.使用substring()toUpperCase()

var str = 'hello world';
var newStr = str.substring(0,1).toUpperCase() + str.substring(1);
console.log(newStr); // Hello world

2.使用slice()toUpperCase()

var str = 'hello world';
var newStr = str.slice(0,1).toUpperCase() + str.slice(1);
console.log(newStr); // Hello world

3.使用charAt()toUpperCase()

var str = 'hello world';
var newStr = str.charAt(0).toUpperCase() + str.slice(1);
console.log(newStr); // Hello world

4.使用replace()

var str = 'hello world';
var newStr = str.replace(/\b\w+\b/g, function(word){
  return word.substring(0,1).toUpperCase() + word.substring(1);
});
console.log(newStr); // Hello world

5.使用split()join()

var str = 'hello world';
var newStr = str.split(' ').map(function(word){
  return word.substring(0,1).toUpperCase() + word.substring(1);
}).join(' ');
console.log(newStr); // Hello world

以上就是js字符串首字母大写的几种实现方法,可根据实际需要选择合适的方法来实现。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。