1

I have created a function that changes a phrase to title case:

function toTitleCase(str) {
  let arr = str.split(' ');
  let x = arr.map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  return x.join(' ');
}

console.log(toTitleCase("A man, a plan, a canal, Panama!"));

I wish I could make this function work like the native toLowerCase(), by changing it to the string, not passing the string as a parameter:

console.log(("A man, a plan, a canal, Panama!").toTitleCase());

How can I achieve that?

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • does this help? https://stackoverflow.com/questions/13521833/javascript-add-method-to-object – limido Sep 17 '20 at 18:24
  • Does this answer your question? [Javascript add method to object](https://stackoverflow.com/questions/13521833/javascript-add-method-to-object) –  Sep 17 '20 at 18:26
  • And here: https://stackoverflow.com/questions/8392035/add-method-to-string-class –  Sep 17 '20 at 18:27

3 Answers3

1

You'll need to add the function to String.prototype:

String.prototype.toTitleCase = function() {
  const arr = this.split(' ');
  const x = arr.map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  return x.join(' ');
}

console.log(("A man, a plan, a canal, Panama!").toTitleCase());

But that's pretty bad practice. A standalone function is better.

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can extend the string prototype.


String.prototype.toTitleCase = function() {
  let arr = this.split(' ');
  let x = arr.map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  return x.join(' ');
}
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
1

All you need to do is assign it to String.prototype although that is is discouraged.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445