时刻js中的大写首字母
Uppercase first letter in moment js
有没有办法使用moment js让第一个字母大写?
Current output:
moment([20016, 0, 29]).fromNow(); // 4 years ago
Expected output:
moment([2016, 0, 29]).fromNow(); // 4 Years Ago
.capitalize {
text-transform: capitalize;
}
应用以下 class 会给你想要的效果。
编辑:
如果 CSS 不是你的菜,这里有几个不同的例子说明如何使用 JS 。
您可以使用 String.prototype.replace()
和 regex
来实现:
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()
也得到一个函数作为第二个参数:
A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr.
这是另一种方式。
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>
有没有办法使用moment js让第一个字母大写?
Current output:
moment([20016, 0, 29]).fromNow(); // 4 years ago
Expected output:
moment([2016, 0, 29]).fromNow(); // 4 Years Ago
.capitalize {
text-transform: capitalize;
}
应用以下 class 会给你想要的效果。
编辑:
如果 CSS 不是你的菜,这里有几个不同的例子说明如何使用 JS
您可以使用 String.prototype.replace()
和 regex
来实现:
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()
也得到一个函数作为第二个参数:
A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr.
这是另一种方式。
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>