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
  • 204,283
  • 31
  • 260
  • 272
Fer
  • 21
  • 1
  • 1
  • 2

3 Answers3

4

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
  • 31,391
  • 7
  • 56
  • 78
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
  • 17,900
  • 5
  • 50
  • 68
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,657
  • 2
  • 13
  • 18