patternjavascriptMinor
Code Concision - String Capitalization
Viewed 0 times
codeconcisionstringcapitalization
Problem
I'm working on a few JavaScript functions for myself that I hope come in handy sometime. The first I wrote was a Capitalization function (yeah i know, real original. whatever)
I was just wondering if
Code:
Thanks!
http://jsfiddle.net/thomas4g/LpwRn/31/
I was just wondering if
- I'm doing anything incredibly stupid
- There's anyway to make the code below more concise (like cool JS concision features i don't know about, tightening down on program flow, etc.)
- There's anything else cool i can do
Code:
String.prototype.capitalize = function(everyWord) {
var words = this.split(" ");
if (everyWord == true) {
for (i = 0; i < words.length; i++) {
words[i] = cap(words[i]);
}
}
else {
words[0] = cap(words[0]);
}
return words.join(" ");
function cap(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
};
var x = "abraham lincoln yada yada";
x = x.capitalize();
alert(x);
x = x.capitalize(true);
alert(x);Thanks!
http://jsfiddle.net/thomas4g/LpwRn/31/
Solution
Live example
Write to
Use underscore and underscore.string.
Basically don't re-invent the wheel ;)
String.capitalize = function(str, everyWord) {
return _.map(_.words(str), function(val, key) {
return key === 0 || everyWord ? _.capitalize(val) : val;
}).join(" ");
};Write to
String not String.prototype. Extending native prototypes is not friendly.Use underscore and underscore.string.
Basically don't re-invent the wheel ;)
Code Snippets
String.capitalize = function(str, everyWord) {
return _.map(_.words(str), function(val, key) {
return key === 0 || everyWord ? _.capitalize(val) : val;
}).join(" ");
};Context
StackExchange Code Review Q#2734, answer score: 4
Revisions (0)
No revisions yet.