是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
与其他答案相比,我更喜欢下面的答案。它只匹配每个单词的第一个字母,并将其大写。更简单的代码,更容易阅读和更少的字节。它保留了现有的大写字母,以防止扭曲的首字母缩写。然而,你总是可以首先在你的字符串上调用toLowerCase()。
function title(str) {
return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
你可以把这个添加到你的字符串原型,这将允许你'my string'.toTitle()如下所示:
String.prototype.toTitle = function() {
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
例子: String.prototype.toTitle = function() { return this.replace(/(^|\s)\ s /g, function(t) {return t. touppercase ()}); } console.log('全部小写->','全部小写'.toTitle()); console.log('所有大写字母->','所有大写字母'.toTitle()); console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
其他回答
这个解决方案将标点符号考虑到新句子中,处理引用,将小词转换为小写,忽略首字母缩写或全大写单词。
var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");
// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
var newSentence = true;
return this.split(/\s+/).map(function(word) {
if (word == "") { return; }
var canCapitalise = true;
// Get the pos of the first alpha char (word might start with " or ')
var firstAlphaCharPos = word.search(/\w/);
// Check for uppercase char that is not the first char (might be acronym or all caps)
if (word.search(/[A-Z]/) > 0) {
canCapitalise = false;
} else if (stopWordsArray.indexOf(word) != -1) {
// Is a stop word and not a new sentence
word.toLowerCase();
if (!newSentence) {
canCapitalise = false;
}
}
// Is this the last word in a sentence?
newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
}).join(' ');
}
// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());
/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
试试这个,最短的方法:
str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
健壮的函数式编程方式做标题大小写函数
Exaplin版本
function toTitleCase(input){
let output = input
.split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
.map((letter) => {
let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y
let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
return firstLetter + restLetters // conbine together
})
.join(' ') //['How' 'Are' 'You'] => 'How Are You'
return output
}
实现版本
function toTitleCase(input){
return input
.split(' ')
.map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
.join(' ')
}
toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
下面是我的函数,它转换为标题大小写,但也保留了定义的首字母缩写为大写,小词为小写:
String.prototype.toTitleCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
return str;
}
例如:
"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
function toTitleCase(str) {
var strnew = "";
var i = 0;
for (i = 0; i < str.length; i++) {
if (i == 0) {
strnew = strnew + str[i].toUpperCase();
} else if (i != 0 && str[i - 1] == " ") {
strnew = strnew + str[i].toUpperCase();
} else {
strnew = strnew + str[i];
}
}
alert(strnew);
}
toTitleCase("hello world how are u");
推荐文章
- 我如何使用可选的链接与数组和函数?
- EINVRES请求https://bower.herokuapp.com/packages/失败,提示502
- 使用fetch进行基本身份验证?
- 如何从子组件内部更新React上下文?
- 如何将一个普通对象转换为ES6映射?
- scrollIntoView卷轴太远了
- Angular ng-repeat反过来
- 如何获得请求路径与表达请求对象
- 使用Handlebars 'each'循环访问父对象的属性
- 盎格鲁- ngcloak / ngg展示blink元素
- 禁用表单自动提交按钮单击
- 节点和错误:EMFILE,打开的文件太多
- JavaScript函数中的默认参数值
- 使用RegExp.exec从字符串中提取所有匹配项
- 测试一个值是奇数还是偶数