下面的代码是我的实现,不知道有没有更好的实现方案。
javascriptString.prototype.firstUpperCase = function(){
return this.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
return $1.toUpperCase() + $2.toLowerCase();
});
}
求接龙。
// RegExp
const firstUpperCase = (str) => {
return str.replace(/(^|\s)[a-z]/g, (y) => y.toUpperCase());
}
// RegExp && splits
const firstUpperCase2 = (str) => {
const splits = str.split(" ");
return splits.map((x) => x.replace(/[a-z]/, (y) => y.toUpperCase())).join(" ");
}
// charAt && substr && splits
const firstUpperCase3 = (str) => {
const splits = str.split(" ");
return splits.map((x) => x.charAt(0).toUpperCase() + x.substr(1)).join(" ");
}
why not use CSS? text-transform: capitalize;can solve this.
you can also use this function:
function firstUpperCase(str) { return str.toLowerCase().replace(/\b[a-z]/g,function(s){return s.toUpperCase();}); }
but if only want to change the initials of the whole strings,try this:
function firstUpperCase(str) { return str.toLowerCase().replace(/^\S/g,function(s){return s.toUpperCase();}); }
String.prototype.firstUpperCase=function(){ return this.replace(/^\S/,function(s){return s.toUpperCase();}); }
String.prototype.firstUpperCase = function () { return this.toString()[0].toUpperCase() + this.toString().slice(1); }
不改变原字符串。(暂时想不到改变原字符串的方式,因为我记得字符串是只读的)
其实有很多方法。
最常见的,最基础的:
1.先split()成数组。
2.将数组中的元素全部小写化。(toLowerCase())
3.使用replace(),toUpperCase()方法将每一项首字母大写化,之后join()就可以了。
但是这样确实很麻烦。
正在学习ES6中,ES6里面解决这个方案这样写就可以了。
function firstUpperCase(str) { return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase()); }
是不是觉得很简洁?
CSS 完全搞定啊 text-transform: capitalize;
这么简单的功能 还用js 就太浪费累