I have this string using JavaScript:
let str = "my city is beautiful."
I would like to get:
"My City Is Beautiful"
I tried this:
str.charAt(0).toUpperCase() + str.slice(1)
But I got:
My city is beautiful
Could you help me please?
I have this string using JavaScript:
let str = "my city is beautiful."
I would like to get:
"My City Is Beautiful"
I tried this:
str.charAt(0).toUpperCase() + str.slice(1)
But I got:
My city is beautiful
Could you help me please?
you can use split
, map
and join
:
"my city is beautiful"
.split(" ")
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join(" ")
Using map
and join
.
let str = "my city is beautiful."
var newStr = str.split(" ").map( str => str.substring(0,1).toUpperCase()+ str.substring(1)).join(' ')
console.log(newStr)
Note the logic here is:
map
and, for each word: Set uppercase to first value and append the rest of the word using substring(1)
.const string = "my city is beautiful.";
const words = string.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
let newString = words.join(" ");
You can:
let str = "my city is beautiful."
const result =
// split up the string into words
str.split(' ')
// capitalize the first letter of each word
.map(word => {
const [firstChar, ...rest] = word;
return [firstChar.toUpperCase(), ...rest].join('');
})
// join the words back into a single string
.join(' ');
console.log(result);
All you need to do is cycle through every word in your string and modify it individually. You can do that using split().
let str = "my city is beautiful."
let newStr = "" // Create temporary string
let words = str.split(" ") // Split the string into words and store them in array
for (word of words) { // Cycle through the array
let newWord = word.charAt(0).toUpperCase() + word.slice(1) // Modify every word in the array
newStr += (newWord + " ") // Append the word to the new String and add a space to the
end
}
console.log(newStr.trim()) // Removes the spaces at the beginning and the end
// Output:
// "My City Is Beautiful."
Or a shorter approach:
let str = "my city is beautiful."
let newStr = ""
for (word of str.split(" "))
newStr += (word.charAt(0).toUpperCase() + word.slice(1) + " ")
console.log(newStr.trim())
// Output:
// "My City Is Beautiful."
Learn how to here:
Basic Algorithm Scripting: Title Case a SentencePassed
freeCodeCamp Challenge Guide: Title Case a Sentence
let str = "my city is beautiful."
let newstr = str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());
console.log(newstr)