0

Please tell me how can I use the injected functions in predefined variables. Here's the script to convert a string into camel case, but I don't know how to use it.

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

Also, tell me if there is any relevancy of using $1 as the arguments! I mean is there any use of $ in this function?

P.S. I took this script from this question.

Sanjay
  • 540
  • 2
  • 13
  • 29

1 Answers1

0

Also, tell me if there is any relevancy of using $1 as the arguments! I mean is there any use of $ in this function?

No, it's just the param's name.

Please tell me how can I use the injected functions in predefined variables. Here's the script to convert a string into camel case, but I don't know how to use it.

  • You only need to instantiate variables of that type (string).
  • The prototype is useful when you need to operate over the specific object, so you don't need to pass a string, rather, use the current context this, in this case, a string.

String.prototype.toCamelCase = function() {
    return this // Here you use the current object using the context 'this'
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

console.log("ele from so".toCamelCase());
Ele
  • 33,468
  • 7
  • 37
  • 75