patternjavascriptModerate
Change case of string, replace hyphens with spaces and capitalize first letter
Viewed 0 times
casechangewithreplacehyphensletterspacesfirstcapitalizeand
Problem
I'm trying to transform the following string "joe-smith" to "Joe Smith". I have the following code which seems to work okay, but is there a faster, better way?
var prettify = function(str){
var temp = str.split('-'), i, pretty;
for(i = 0; i < temp.length; i++){
temp[i] = temp[i].charAt(0).toUpperCase() + temp[i].slice(1);
}
pretty = temp.join(' ');
return pretty;
};
var prettyString = prettify('joe-smith');
// outputs "Joe Smith"Solution
Some things:
-
You could use the Array
-
regular expressions and the String
Decide yourself whether this is too cryptic or not.
- That
prettyvariable is pretty useless. Omit it.
tempis quite meaningless. Use a descriptive name likewordsorparts.
-
You could use the Array
map method instead of that for loop. This will likely be slower, but more elegant:function prettify(str) {
return str.split('-').map(function capitalize(part) {
return part.charAt(0).toUpperCase() + part.slice(1);
}).join(' ');
}-
regular expressions and the String
replace method could further shorten it, and possibly improve performance:function prettify(str) {
return str.replace(/(-|^)([^-]?)/g, function(_, prep, letter) {
return (prep && ' ') + letter.toUpperCase();
});
}Decide yourself whether this is too cryptic or not.
Code Snippets
function prettify(str) {
return str.split('-').map(function capitalize(part) {
return part.charAt(0).toUpperCase() + part.slice(1);
}).join(' ');
}function prettify(str) {
return str.replace(/(-|^)([^-]?)/g, function(_, prep, letter) {
return (prep && ' ') + letter.toUpperCase();
});
}Context
StackExchange Code Review Q#87221, answer score: 10
Revisions (0)
No revisions yet.