Hi! I'm Mayu.
In this post, I introduce how to change letter's case in JavaScript.
Now, here is a sentence about me.
i LOVE JaVa SpaRRoW!
How do you feel when you read this sentence?
A little weird...is it?
(By the way, recently I realized this is an expression of interesting intonation. I didn't know this before I started learning English, so I am happy about this realization!)
So, let's make function to the sentence to be more readable :)โจ
function changeLetter(text) {
let word = text.split(" ");
let arr =[];
for(let i= 0; i < word.length; i++){
arr.push(word[i].charAt(0).toUpperCase() + word[i].substring(1).toLowerCase());
}
return arr.join(" ");
}
console.log(changeLetter('i LOVE JaVa SpaRRoW!'));
// I Love Java Sparrow!
1. Set space as separater and split sentences into words.
- split() to split sentence with spaces(" ").
2. Add elements that capitalized only the first letter to the array.
- use loop because each texts have more than 2 words.
- charAt() method that returns new string
- toUpperCase() method returns the calling string value converted to uppercase
- substring() method that returns the part of the string
- toLowerCase() method returns the calling string value converted to lowercase
- push() method that adds elements to the end of an array
3. Return to a sentence with a space between words.
- join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string.
reference: mdn
Top comments (0)