I have made this code. I want a small regexp for this.
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());
What i want
"hello world".initCap() => Hello World
"hEllo woRld".initCap() => Hello World
my above code gives me solution but i want a better and faster solution with regex
You can try:
str = "hEllo woRld";
String.prototype.initCap = function () {
return this.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) {
return m.toUpperCase();
});
};
console.log(str.initCap());