Uppercase first letter in moment js

Viewed 1035

Is there a way to have just the first letter in uppercase using momment js?

Current output:

moment([20016, 0, 29]).fromNow(); // 4 years ago


Expected output:

moment([2016, 0, 29]).fromNow(); // 4 Years Ago

3 Answers
  .capitalize {
   text-transform: capitalize;
  }

Applying the following class will give you the desired effect.

Edit:

If CSS isn't your thing, there is a few different examples of how to do it using JS here.

You can use String.prototype.replace() with regex to achieve this:

console.log(moment([2016, 0, 29]).fromNow().replace(/\b[a-z]/, match => match.toUpperCase()));
<script src="https://momentjs.com/downloads/moment.js"></script>

String.prototype.replace() also gets a function as a second argument:

A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr.

String.prototype.replace()

Here's another way.

console.log(moment([2016, 0, 29]).fromNow().split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' '));
<script src="https://momentjs.com/downloads/moment.js"></script>

Related