大写数组中每个单词的第一个字母 [英] Capitalize the first letter of every word in array

查看:124
本文介绍了大写数组中每个单词的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

var myarr = [ "color - black", "color - blue", "color - Red" ]

我希望将 - 替换为:并将首字母大写该数组中的每个单词:

And I want want to replace " - " with ":" and capitalize the first letter of every word in that array:

var myarr = [ "Color: Black", "Color: Blue", "Color: Red" ]

我试试

for (var i = 0; i < myarr.length; i++) {
  myarr[i] = myarr[i][0].toUpperCase()+myarr[i].replace(/ -/g, ":").substring(1);
}

但它仅适用于第一个单词

But it works only for the first word

推荐答案

您可以使用另一个正则表达式在函数中为其大写字母交换字母。这样的东西会起作用:

You can use another regex to swap letters for their capitals in a function. Something like this will work:

String.prototype.capitalize = function() {
    return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};


var myarr = [ "color - black", "color - blue", "color - Red" ]

for(var i=0; i < myarr.length; i++) {
    myarr[i] = myarr[i].capitalize().replace(/ -/g, ":");
}

console.log(myarr)

你可以看到它在这里工作: https://jsfiddle.net/igor_9000/c7tqraLo/
最初的问题在这里:大写字母串中的单词

You can see it working here: https://jsfiddle.net/igor_9000/c7tqraLo/ The original SO question here: Capitalize words in string

这篇关于大写数组中每个单词的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆