字符串中每个单词首字母大写
一、正常思路 使用for循环
function titleCase(str){
var a = str.toLowerCase().split(' ');
var len = a.length;
var b = [];
for(i=0;i<len;i++){
a[i] = a[i][0].toUpperCase() + a[i].slice(1);
}
b = a.join(' ');
return b;
}
var title = titleCase("I'm a little tea pot");
console.log(title);//I'm A Little Tea Pot
二、map+数组
function titleCase(str){
var a = str.toLowerCase().split(' ');
var b = a.map(function(item){
return item[0].toUpperCase() + item.slice(1);
});
return b.join(' ');
}
var title = titleCase("I'm a little tea pot");
console.log(title);//I'm A Little Tea Pot
三、数组+reduce
function titleCase(str){
var a = str.toLowerCase().split(' ');
var b = a.reduce(function(prev,cur){
return prev[0].toUpperCase()+prev.slice(1) + ' '+cur[0].toUpperCase() + cur.slice(1);
});
return b;
}
var title = titleCase("I'm a little tea pot");
console.log(title);//I'm A Little Tea Pot
四、正则表达式+replace
function titleCase(str){
var a = str.toLowerCase().replace(/\b([\w|']+)\b/g,function(s){
return s.slice(0,1).toUpperCase()+s.slice(1);
});
return a;
}
var title = titleCase("I'm a little tea pot");
console.log(title);//I'm A Little Tea Pot
五、正则表达式(es6语法)
function titleCase(str){
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}
var title = titleCase("I'm a little tea pot");
console.log(title);//I'm A Little Tea Pot
注:纯属个人学习笔记。
网友评论