2

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.

3

3 Answers 3

5

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

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

0
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.