How can I convert a toTitleCase function into a "native" JavaScript string method?

Viewed 120

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?

3 Answers

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.

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

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

Related