是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
下面是我的函数,它负责处理重音字符(对法语来说很重要!),并且可以打开/关闭对lower异常的处理。希望这能有所帮助。
String.prototype.titlecase = function(lang, withLowers = false) {
var i, string, lowers, uppers;
string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/Mc(.)/g, function(match, next) {
return 'Mc' + next.toUpperCase();
});
if (withLowers) {
if (lang == 'EN') {
lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
}
else {
lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
}
for (i = 0; i < lowers.length; i++) {
string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
return txt.toLowerCase();
});
}
}
uppers = ['Id', 'R&d'];
for (i = 0; i < uppers.length; i++) {
string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
}
return string;
}
其他回答
我的清单是基于三个快速搜索。一个用于不大写的单词列表,一个用于完整的介词列表。
最后一个搜索建议,5个或5个字母以上的介词应该大写,这是我喜欢的。我的目的是非正式使用。我把“without”留在了他们的单词里,因为它是with的明显对应词。
所以它把首字母缩写,标题的第一个字母,以及大多数单词的第一个字母都大写。
它不打算处理带有大写锁的单词。我不想管这些。
function camelCase(str) { return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) { return character.toUpperCase(); })} console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));
这个解决方案将标点符号考虑到新句子中,处理引用,将小词转换为小写,忽略首字母缩写或全大写单词。
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.slice(0, 1).toUpperCase() + str.slice(1, str.length)
*如果你想要小写单词的其余部分,在结尾添加.toLowerCase()
使用ES6扩展操作符、映射和Join
[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')
瓦尔·弦=“测试” 笨蛋。 var输出=弦。charAt(0) 控制台日志(输出)。 警报(输出)
var string = "tEsT"
string = string.toLowerCase()
string.charAt(0).toUpperCase() + string.slice(1)
string.charAt(0) returns the character at the 0th index of the string. toUpperCase() is a method that returns the uppercase equivalent of a string. It is applied to the first character of the string, returned by charAt(0). string.slice(1) returns a new string that starts from the 1st index (the character at index 0 is excluded) till the end of the string. Finally, the expression concatenates the result of toUpperCase() and string.slice(1) to create a new string with the first character capitalized.
有一些很好的答案,但是,许多人使用正则表达式来查找单词,但是,由于某种原因,没有人使用正则表达式来替换第一个字符。为了解释,我将提供一个较长的解决方案和一个较短的解决方案。
长期解决方案(更具解释性)。通过使用正则表达式[^\s_\-/]*,我们可以找到句子中的每一个单词。随后,我们可以使用正则表达式。与单词中的第一个字符匹配。使用正则表达式版本的replace来替换这两个函数,我们可以像这样更改解决方案:
function toUpperCase(str){返回str.toUpperCase();} 函数capitalizeWord(word){返回word.replace(/。/,包含);} 函数大写(句子){返回句子。tolowercase()。替换(/ [/ ^ \ s_ \] * / g, capitalizeWord);} console.log(大写(“hello world”));//输出:Hello World
对于做同样事情的单个函数,我们将replace调用嵌套如下:
函数大写(句子){ 返回sentence.toLowerCase()。替换(/[^\s_\-/]*/g, function (word) { 返回word.replace(/。/,函数(ch){返回ch. touppercase ();}); }); } console.log(大写(“hello world”));//输出:Hello World
推荐文章
- 使用jQuery改变输入字段的类型
- 在JavaScript中,什么相当于Java的Thread.sleep() ?
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?