简体   繁体   中英

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:

 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() . Use .charAt(0) to selecting first character of string and use .slice() to selecting next part of string

 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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