Skip to content Skip to sidebar Skip to footer

Capitalize First Letter Of A Camelcase String In Javascript

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 = func

Solution 1:

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());

Solution 2:

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());

Solution 3:

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!


Post a Comment for "Capitalize First Letter Of A Camelcase String In Javascript"