4

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

Pep
  • 647
  • 6
  • 20
  • 1
    Not an answer, since momentjs might have a built-in way to do it -- but would https://www.npmjs.com/package/title-case suit your needs? – Brandon Nov 11 '20 at 16:48
  • According to https://github.com/moment/moment/issues/5031, one of the Moment js maintainer said "I don't think capitalization preferences should be a concern in Moment.js ." So use the link @TrentBing just offered – Andrea Coluzzi Nov 11 '20 at 16:52

3 Answers3

3
  .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.

groul
  • 119
  • 1
  • 9
0

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()

zb22
  • 3,126
  • 3
  • 19
  • 34
0

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>
DaffyDuck
  • 182
  • 2
  • 6