【发布时间】:2021-05-06 23:57:32
【问题描述】:
我有这个使用 JavaScript 的字符串:
let str = "my city is beautiful."
我想得到:
"My City Is Beautiful"
我试过这个:
str.charAt(0).toUpperCase() + str.slice(1)
但我得到了:
My city is beautiful
你能帮帮我吗?
【问题讨论】:
标签: javascript
我有这个使用 JavaScript 的字符串:
let str = "my city is beautiful."
我想得到:
"My City Is Beautiful"
我试过这个:
str.charAt(0).toUpperCase() + str.slice(1)
但我得到了:
My city is beautiful
你能帮帮我吗?
【问题讨论】:
标签: javascript
您可以使用split、map 和join:
"my city is beautiful"
.split(" ")
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join(" ")
【讨论】:
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(" ");
【讨论】:
使用map 和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)
注意这里的逻辑是:
map 进行迭代,并且对于每个单词:将第一个值设置为大写,并使用substring(1) 附加单词的其余部分。【讨论】:
您需要做的就是循环遍历字符串中的每个单词并单独修改它。 您可以使用 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."
或者更短的方法:
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."
【讨论】:
你可以:
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);
【讨论】:
在此处了解如何操作:
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)
【讨论】: