3

I have a string like "word_count". How can I transform it to "WordCount" in an elegant way using JavaScript? My decision seems too complicated to me. I'll be very grateful for your help.

Grizerg
  • 149
  • 6
  • 10

10 Answers10

7
function titleCase(str)
{
    return str.split("_")
        .map(function (s) { return s.charAt(0).toUpperCase() + s.slice(1); })
        .join("");
}
Anthony Mills
  • 8,676
  • 4
  • 32
  • 51
4

Take a look at this. I don't want to just copy paste everything here, but it seems to be just what you're looking for.

Here is the function modified to fit your request:

String.prototype.toCamel = function(){
    return this.replace(/((^|\_)[a-z])/g, function($1){
                return $1.toUpperCase().replace('_','');});
};

And here it is in action.

HRÓÐÓLFR
  • 5,842
  • 5
  • 32
  • 35
3

You can use a regular expression to match either a letter at the start of the string or a letter after an underscore, and use a callback to turn the letter into uppercase:

s = s.replace(/(?:^|_)([a-z])/g, function(m, g){
  return g.toUpperCase();
});

Demo: http://jsfiddle.net/Guffa/ByU6P/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2

Simple, like this:

var string = "word_count".split("_");
for(var i = 0; i<string.length;i++) {
    string[i] = string[i].charAt(0).toUpperCase() + string[i].substr(1);
}
var myNiceString = string.join();

If you want to add it to the String object, you can do this:

String.prototype.titleCase = function() {
    var split = this.split("_");
    for(var i = 0; i<split.length;i++) {
        split[i] = split[i].charAt(0).toUpperCase() + split[i].substr(1);
    }
    return split.join("");
}

You'd call it like "word_count".titleCase();

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
1

You can use a function like the following:

var Pascalize = function(word) {
    var x = word;
    result = '';
    if(-1 != word.indexOf('_')) {
        x = word.split('_');
        for(var i=0;i<x.length;i++) {
            result += x[i].substr(0, 1).toUpperCase() + x[i].substr(1);
        }
    }
    if('' == result) { result = word; }
    return result;
};

var PascalCaseString = Pascalize("this_is_a_test");
// PascalCaseString value is now 'ThisIsATest'

Here's a working example

MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53
0
var str = "word_count";
var re = /\b(.)([^_]+)_(.)/;
var newWord = str.replace(re, function(m,f,t,l){ return f.toUpperCase() + t + l.toUpperCase();})
console.log(newWord);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Using jQuery, you could do the following:

var result = '';
$.each('word_count'.split('_'), function(idx,elem){
  result = result + elem.substr(0,1).toUpperCase() + elem.substr(1);
});
Liggy
  • 1,181
  • 2
  • 11
  • 19
0

New version (works with any amount of _):

function fixString(sString) {

    var aWords = sString.split("_"),
        sResults = "";

    for (var i in aWords)
        sResults += aWords[i].charAt(0).toUpperCase() + aWords[i].slice(1);

    return sResults;

}

The compressed form:

function fixString(c){var d=c.split("_"),a="";for(var b in d){a+=d[b].charAt(0).toUpperCase()+d[b].slice(1)}return a};

Old:

function fixString(sString) {

    return sString.replace(/(.*)_(.*)/, function(sWhole, $1, $2, sWTF) {

        return ucfirst($1) + ucfirst($2);

    } )

    function ucfirst (str) {

        str += '';

        var f = str.charAt(0).toUpperCase();

        return f + str.substr(1);

    }

}

... or the compressed version:

function fixString(b){return b.replace(/(.*)_(.*)/,function(e,c,f,d){return a(c)+a(f)});function a(d){d+="";var c=d.charAt(0).toUpperCase();return c+d.substr(1)}};

Of course, this is used like fixString("word_count") which results in your desired WordCount.

Gabriel Ryan Nahmias
  • 2,135
  • 2
  • 26
  • 39
0

I've looked at all the answer and none did precisely what I wanted. I wanted an idempotent function which converted to camelCase (not PascalCase) and I liked the String prototype extension approach (although obviously this isn't always the best medicine).

Anyway, here's where I ended up:

String.prototype.camelize = function(){
    var pascalCase = this.replace(/((^|\_)[a-z])/g, function($1){
        return $1.toUpperCase().replace('_','');
    });
    return pascalCase.charAt(0).toLowerCase() + this.slice(1);
};
ken
  • 8,763
  • 11
  • 72
  • 133
-1
var aStringLike = "word_count";

// magic follows

aStringLike = "WordCount";
Hogan
  • 69,564
  • 10
  • 76
  • 117