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,237
  • 4
  • 24
  • 201
  • 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) – ChrisG Sep 17 '20 at 18:26
  • And here: https://stackoverflow.com/questions/8392035/add-method-to-string-class – ChrisG 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,237
  • 4
  • 24
  • 201
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
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,237
  • 4
  • 24
  • 201
Abir Taheer
  • 1,818
  • 1
  • 7
  • 25
1

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

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430