javascript 标题案例一个句子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31495239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Title case a sentence?
提问by natalie
I'm trying to proper case a string in javascript - so far I have this code: This doesn't seem to capitalize the first letter, and I'm also stuck on how to lowercase all the letters after the first letter.
我正在尝试在 javascript 中正确区分大小写 - 到目前为止,我有以下代码:这似乎没有将第一个字母大写,而且我还坚持如何将第一个字母之后的所有字母小写。
function titleCase(str) {
var newstr = str.split(" ");
for(i=0;i<newstr.length;i++){
newstr[i].charAt(0).toUpperCase();
}
newstr = newstr.join(" ");
return newstr;
}
To be clear, I want every single word in the sentence to be capitalized.
明确地说,我希望句子中的每个单词都大写。
采纳答案by JCOC611
This should work. Notice how I set newstr[i]
to the desired output. Functions like .toUpperCase()
do not affect the original string. They only return a newstring with the desired property.
这应该有效。请注意我如何设置newstr[i]
为所需的输出。像.toUpperCase()
这样的函数不影响原始字符串。它们只返回具有所需属性的新字符串。
function titleCase(str) {
var newstr = str.split(" ");
for(i=0;i<newstr.length;i++){
if(newstr[i] == "") continue;
var copy = newstr[i].substring(1).toLowerCase();
newstr[i] = newstr[i][0].toUpperCase() + copy;
}
newstr = newstr.join(" ");
return newstr;
}
回答by Rob Jens
One of the cleanest ways I can come up with, using ES6, while still lacking a proper .capitalize()
string prototype method:
我能想到的最简洁的方法之一,使用 ES6,但仍然缺乏合适的.capitalize()
字符串原型方法:
let sent = "these are just some words on paper"
sent.split(' ').map ( ([h, ...t]) => h.toUpperCase() + t.join('').toLowerCase() )
Uses destructuring on array element strings to obtain head and tail via spread operator (making tail a sequence of characters) which are first joined before coerced to lower case. Or you could replace that with a s => s[0].toUpperCase() + s.substring(1).toLowerCase()
I guess. Oh, since the question seems to indicate ES5, transformation is cheap although noticeably more verbose:
对数组元素字符串使用解构,通过扩展运算符(使尾部成为字符序列)获得头部和尾部,在强制转换为小写之前首先连接。或者你可以用s => s[0].toUpperCase() + s.substring(1).toLowerCase()
我猜替换它。哦,因为这个问题似乎表明 ES5,所以转换很便宜,虽然明显更冗长:
function capitalize (sentence) {
return sentence.split(' ').map(
function (s) {
return s[0].toUpperCase() + s.substring(1).toLowerCase()
}).join(' ') ;
}
That is, assuming you'd want another sentence returned.
也就是说,假设您希望返回另一个句子。
回答by Matt Jesuele
If you enjoy using Ramdalike I do, you can do this clean fun thing:
如果你像我一样喜欢使用Ramda,你可以做这个干净有趣的事情:
import { concat, compose, head, join, map, split, tail, toLower, toUpper } from 'ramda';
const toWords = split(' ');
const capitalizeWords = map(s => concat(toUpper(head(s)), toLower(tail(s))));
const toSentence = join(' ');
const toTitleCase = compose(toSentence, capitalizeWords, toWords);
or of course you can always cut it down to
或者当然你总是可以把它减少到
const capitalizeWords = map(s => concat(toUpper(head(s)), toLower(tail(s))));
const toTitleCase = compose(join(' '), capitalizeWords, split(' '));
回答by Maximillian Laumeister
Here is a working piece of code. The problematic line in your code was this one:
这是一段工作代码。您的代码中有问题的那一行是:
newstr[i].charAt(0).toUpperCase();
That line gets the uppercased first letter of each word, but it doesn't do anything with it. The way the code below works is that it uppercases the first character, then appends the rest of the word, then assigns that back into newstr[i]
.
该行获取每个单词的大写首字母,但对它没有任何作用。下面的代码的工作方式是将第一个字符大写,然后附加单词的其余部分,然后将其分配回newstr[i]
.
function titleCase(str) {
var newstr = str.split(" ");
for(i=0;i<newstr.length;i++){
newstr[i] = newstr[i].charAt(0).toUpperCase() + newstr[i].substring(1).toLowerCase();
}
newstr = newstr.join(" ");
return newstr;
}
回答by Reflective
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
This function uppercases 1st letter and lowercases the rest part od the string.
此函数将第一个字母大写,并将字符串的其余部分小写。
A bit changed function from the perfect answer found here: How do I make the first letter of a string uppercase in JavaScript?
在这里找到的完美答案的功能略有变化:如何在 JavaScript 中使字符串的第一个字母大写?
回答by Harry Stevens
Here's a function titleCase(string, array)
that transforms a string into title case, where the first letter of every word is capitalized except for certain prepositions, articles and conjunctions. If a word follows a colon, it will always be capitalized. You can include an optional array to ignore strings of your choice, such as acronyms.
这function titleCase(string, array)
是将字符串转换为标题大小写的 a ,其中每个单词的第一个字母都大写,但某些介词、冠词和连词除外。如果一个单词跟在冒号之后,它总是大写。您可以包含一个可选数组来忽略您选择的字符串,例如首字母缩略词。
I may have missed some exception words in the ignore
array. Feel free to add them.
我可能遗漏了ignore
数组中的一些异常词。随意添加它们。
function titleCase(str, array){
var arr = [];
var ignore = ["a", "an", "and", "as", "at", "but", "by", "for", "from", "if", "in", "nor", "on", "of", "off", "or", "out", "over", "the", "to", "vs"];
if (array) ignore = ignore.concat(array);
ignore.forEach(function(d){
ignore.push(sentenceCase(d));
});
var b = str.split(" ");
return b.forEach(function(d, i){
arr.push(ignore.indexOf(d) == -1 || b[i-1].endsWith(":") ? sentenceCase(d) : array.indexOf(d) != -1 ? d : d.toLowerCase());
}), arr.join(" ");
function sentenceCase(x){
return x.toString().charAt(0).toUpperCase() + x.slice(x.length-(x.length-1));
}
}
var x = titleCase("james comey to remain on as FBI director", ["FBI"]);
console.log(x); // James Comey to Remain on as FBI Director
var y = titleCase("maintaining substance data: an example");
console.log(y); // Maintaining Substance Data: An Example
回答by ZhaoWeihao
First all become lowercase, and then open each word, and then open each letter, the first letter set capital, and then together
首先全部变成小写,然后打开每个单词,再打开每个字母,第一个字母设置大写,然后一起
function titleCase(str) {
var copy=str;
copy=copy.toLowerCase();
copy=copy.split(' ');
for(var i=0;i<copy.length;i++){
var cnt=copy[i].split('');
cnt[0]=cnt[0].toUpperCase();
copy[i]=cnt.join('');
}
str=copy.join(' ');
return str;
}
titleCase("I'm a little tea pot");
回答by Anthony Lorenzo
function titleCase(str) {
var titleStr = str.split(' ');
for (var i = 0; i < titleStr.length; i++) {
titleStr[i] = titleStr[i].charAt(0).toUpperCase() + titleStr[i].slice(1).toLowerCase();
}
return titleStr.join(' ');
}
titleCase("i'm a little tea pot")
回答by BillyD
I recently redid this problem using regex which matches the first letter and accounts for apostrophe. Hope it's helpful:
我最近使用匹配第一个字母和撇号的正则表达式重新解决了这个问题。希望有帮助:
function titleCase(str) {
return str.toLowerCase().replace(/^\w|\s\w/g, function(firstLetter) {
return firstLetter.toUpperCase();
});
}
titleCase("I'm a little tea pot");
回答by Gustoko
My Solution
我的解决方案
function titleCase(str) {
var myArr = str.toLowerCase().split(" ");
for (var a = 0; a < myArr.length; a++){
myArr[a] = myArr[a].charAt(0).toUpperCase() + myArr[a].substr(1);
}
return myArr.join(" ");
}