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());
Fiddle
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());
If you want to account for names with an apostrophe/dash or if a space could potentially be omitted after a period between sentences, then you might want to use \b (beg or end of word) instead of \s (whitespace) in your regular expression to capitalize any letter after a space, apostrophe, period, dash, etc.
str = "hEllo billie-ray o'mALLEY-o'rouke.Please come on in.";
String.prototype.initCap = function () {
return this.toLowerCase().replace(/(?:^|\b)[a-z]/g, function (m) {
return m.toUpperCase();
});
};
alert(str.initCap());
OUTPUT: Hello Billie-Ray O'Malley-O'Rouke.Please Come On In.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With