I am trying to capitalize the first letter of the word, and replace it with smaller first letter of the word. I am done till, capitalizing the first letter but I do not know how to join the first letter with the rest of the letter in the word.
let a="i am using stack overflow and it is great";
function makeCapital(){
const words=a.split(" ");
console.log(words);
const firstLetter = words.map(letter=>letter.charAt(0));
console.log(firstLetter);
const capitalLetter=firstLetter.map(capital=>capital.toUpperCase());
console.log(capitalLetter);
}
//I do not know how to join this capiltal letter with rest of the letters in a word
makeCapital();
CodePudding user response:
You're overcomplicating things here a bit. You can just loop through every word in the sentence (your words
array here) and uppercase each of them, then join them back:
const capitalizedWords = words.map(word => word.charAt(0).toUppercase() word.slice(1)));
const capitalizedSentence = capitalizedWords.join(" ");
slice
method resturns a portion of an array, given a start and an end(optional) index.
CodePudding user response:
From your code it looks like you want to capitalize all the words in the string, so this could help:
"I don't know".split(" ").map(word => word[0].toUpperCase() word.substring(1)).join(" ")
# => I Don't Know
CodePudding user response:
You can use join() on a array of string to "glue it back" to a string
So, if you need to capitalize the first letter of each word, you can do this :
const str = "i am using stack overflow and it is great";
const res = str
.split(" ")
.map((w) => { return w[0].toUpperCase() w.substring(1); })
.join(" ");
console.log(res); // I Am Using Stack Overflow And It Is Great
CodePudding user response:
Assuming that you want to capitalize each word of your sentence and want to have something like:
"I Am Using Stack Overflow And It Is Great"
You can achieve it with following code:
makeCapital = (words) =>
words.split(" ").map(element =>
element.charAt(0).toUpperCase() element.substring(1).toLowerCase()
).join(" ");
makeCapital("i am using stack overflow and it is great");
Reference: https://bobbyhadz.com/blog/javascript-capitalize-first-letter-of-each-word-in-array
Or did I misunderstand you?
CodePudding user response:
CSS solution
If you wish to apply capitals to each word in a sentence for display purposes, it is easily (and arguably better) achieved with css using text-transform: capitalize;
All major browsers support this rule, see: https://caniuse.com/?search=text-transform
If you need to do this dynamically, the style can be set using JS.
The following snippet demonstrates both static and dynamic styling using css:
function change() {
document.getElementsByTagName('p')[1].style="text-transform: capitalize;";
}
p.styled {
text-transform: capitalize;
}
<p >i am using stack overflow and it is great</p>
<p>i am using stack overflow and it is great</p>
<button onclick="change()">capitalise</button>