HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Change case of string, replace hyphens with spaces and capitalize first letter

Submitted by: @import:stackexchange-codereview··
0
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:

  • That pretty variable is pretty useless. Omit it.



  • temp is quite meaningless. Use a descriptive name like words or parts.



-
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.