Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
TehBrackShiip Avatar asked Sep 07 '25 03:09

TehBrackShiip


2 Answers

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);
like image 167
slider Avatar answered Sep 10 '25 11:09

slider


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>
like image 45
Mohammad Avatar answered Sep 10 '25 11:09

Mohammad