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字符串首字母大写的几种实现方法,可根据实际需要选择合适的方法来实现。