1

I'm trying to obtain a camel case string (but with the first letter capitalized).

I'm using the following regular expression code in JavaScript:

String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
    if (p2) return p2.toUpperCase();
    return p1.toLowerCase();
});

but the first letter is converted to a lower case.

j08691
  • 197,815
  • 30
  • 248
  • 265
Fer
  • 21
  • 1
  • 1
  • 2

3 Answers3

3

I would not encourage extending String in JavaScript, but anyway to return your string with the first letter in uppercase you can do it like this:

String.prototype.toCamelCase = function() {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
};

Demo:

    String.prototype.toCamelCase = function() {
        return this.substring(0, 1).toUpperCase() + this.substring(1);
    };
    
var str = "abcde";
 console.log(str.toCamelCase());
cнŝdk
  • 30,215
  • 7
  • 54
  • 72
1

String.prototype.toCamelCase = function() {
  return this.replace(/\b(\w)/g, function(match, capture) {
    return capture.toUpperCase();
  }).replace(/\s+/g, '');
}

console.log('camel case this'.toCamelCase());
console.log('another string'.toCamelCase());
console.log('this is actually camel caps'.toCamelCase());
KevBot
  • 16,116
  • 5
  • 48
  • 66
0
String.prototype.toCamelCase = function() {
   string_to_replace = this.replace(/^([A-Z])|\s(\w)/g, 
      function(match, p1, p2, offset) {
         if (p2) return p2.toUpperCase();
         return p1.toLowerCase();
      });
   return string_to_replace.charAt(0).toUpperCase() + string_to_replace.slice(1);
}

One simple way would be to manually uppercase the first character!

Neurax
  • 3,327
  • 2
  • 11
  • 17