Tus*_*har 3 javascript regex string camelcasing
我已经制作了这段代码.我想要一个小的正则表达式.
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.initCap = function () {
var new_str = this.split(' '),
i,
arr = [];
for (i = 0; i < new_str.length; i++) {
arr.push(initCap(new_str[i]).capitalize());
}
return arr.join(' ');
}
alert("hello world".initCap());
Run Code Online (Sandbox Code Playgroud)
我想要的是
"你好世界".initCap()=> Hello World
"hEllo woRld".initCap()=> Hello World
我的上面的代码给了我解决方案,但我想要一个更好,更快的解决方案与正则表达式
anu*_*ava 16
你可以试试:
str = "hEllo woRld";
String.prototype.initCap = function () {
return this.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) {
return m.toUpperCase();
});
};
alert(str.initCap());
Run Code Online (Sandbox Code Playgroud)