简体   繁体   English

使用JavaScript将每个数组元素的首字母大写

[英]Capitalize first letter of each array element using JavaScript

I have a string of text that I've split into an array on each comma. 我有一个字符串,每个逗号都分成一个数组。 I then looped through the array and added each element to a string, one by one, but separated them using a line break. 然后,我遍历数组,并将每个元素一个一个地添加到字符串中,但使用换行符将它们分隔开。

var beg2 = document.twocities.begins.value;
var ans22 = "";
var words2 = beg2.split(",");

for(var i=0; i<words2.length; i++){
    ans22 += words2[i] + "<br>"; 
}

document.getElementById("ans22").innerHTML = ans22;

Now I'm trying to capitalize the first letter of each line using this code but only the first letter of the entire string ends up getting capitalized as opposed to the first on each line. 现在,我尝试使用此代码将每一行的首字母大写,但只有整个字符串的首字母最终变成大写,而不是每一行的首字母。

var ans23 = "";

for (var i=0; i<words2.length; i++){
    firstLetter = words[i].charAt(0);
    firstLetterCap = words[i].charAt(0).toUpperCase();
    words[i].replace(firstLetter,firstLetterCap);
    ans23 += words2[i] + "<br>"; 
}

Any suggestions would be greatly appreciated. 任何建议将不胜感激。

You can simplify this considerably with map by transforming each word in the sentence to its capitalized version and then joining the array back into a sentence: 您可以使用map大大简化此过程,方法是将句子中的每个单词转换为大写形式,然后将数组重新组合成一个句子:

 var sentence = 'hello world test'; var capitalized = sentence .split(' ') .map(w => w.charAt(0).toUpperCase() + w.slice(1)) .join('<br>'); console.log(capitalized); 

You don't need to use .replace() . 您不需要使用.replace() Use .charAt(0) to selecting first character of string and use .slice() to selecting next part of string 使用.charAt(0)选择字符串的第一个字符,并使用.slice()选择字符串的下一部分

 var beg2 = "first,second,third"; var ans22 = ""; var words = beg2.split(","); for (var i=0; i<words.length; i++){ words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); ans22 += words[i] + "<br>"; } document.getElementById("ans22").innerHTML = ans22; 
 <div id="ans22"></div> 

Also you can use CSS ::first-letter pseudo-element and text-transform property to do this work. 您也可以使用CSS ::first-letter伪元素和text-transform属性来完成此工作。

 var str = "first,second,third"; document.getElementById("ans22").innerHTML = str.split(",").map(function(val){ return "<div>"+val+"</div>" }).join(""); 
 #ans22 div::first-letter { text-transform: capitalize; } 
 <div id="ans22"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM