1

I wrote this code:

String.prototype.toJadenCase = function () {
  return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}

let text = 'hello world'
text.toJadenCase()
alert(text) // hello world

And it doesn't change the value of string, from that function called is. As I saw here: String prototype changing the string value , it should work, but it doesn't

Thanks for all the help!

  • Since String.prototype.toJadenCase() returns a value and does not change the original string, text.toJadenCase() does nothing. Instead, use `text = text.toJadenCase()` or something similar. – Yousername Apr 28 '20 at 17:22
  • 1
    I *highly* recommend you avoid assigning protoype properties with the `=` operator. Instead use `Object.defineProperty(String.prototype, 'toJadenCase', { value: function() { /* ... */ }, enumerable: false });`. This avoids polluting enumeration with `for ... in` loops. – Gershom Maes Apr 28 '20 at 17:25
  • @Gershom - Although to be fair, `for-in` on strings is a fairly dodgy thing to do. ;-) (But you're right about using `defineProperty`. Typically you'd make it writable and configurable, not enumerable. [They all default to false.]) – T.J. Crowder Apr 28 '20 at 17:26
  • 1
    That's right @T.J.Crowder! I want to endorse `Object.defineProperty` without endorsing string `for-in` :-P – Gershom Maes Apr 28 '20 at 17:36

2 Answers2

2

You can't change the value of a string, strings are immutable. All you can do is create a new string and return it:

    text = text.toJadenCase()
//  ^^^^^^^

String.prototype.toJadenCase = function () {
  return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}

let text = 'hello world'
text = text.toJadenCase()
alert(text) // hello world

Side note: It's less important with String.prototype than with some others, but best practice is to define anything you add to the built-in prototypes (if you add anything to them at all) as non-enumerable, which is the default when you use Object.defineProperty:

Object.defineProperty(String.prototype, "toJadenCase", {
    value: function () {
        return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
    },
    writable: true,
    configurable: true
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Change text.toJadenCase() to let text = 'hello world'.toJadenCase()

String.prototype.toJadenCase = function() {
  return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}

let text = 'hello world'.toJadenCase()
console.log(text)
brk
  • 48,835
  • 10
  • 56
  • 78