是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
吉姆-鲍勃->吉姆-鲍勃
吉姆/鲍勃->吉姆/鲍勃
jim_bob -> jim_bob
不是->不是
学校->学校
麦当劳->麦当劳
function toTitleCase(str) {
return str.replace(/\p{L}+('\p{L}+)?/gu, function(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1)
})
}
其他回答
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
return i.toUpperCase() + (r != null ? r : "");
}
)
似乎有用… 用上面的测试,“快棕色的狐狸?/跳过/越过了……“C:/程序文件/某些供应商/他们的第二个应用程序/a file1.txt”。
如果你想要2Nd而不是2Nd,你可以更改为/([a-z])(\w*)/g。
第一种形式可以简化为:
function toTitleCase(toTransform) {
return toTransform.replace(/\b([a-z])/g, function (_, initial) {
return initial.toUpperCase();
});
}
这个解决方案将标点符号考虑到新句子中,处理引用,将小词转换为小写,忽略首字母缩写或全大写单词。
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. */
如果你担心这些填充词,你可以告诉函数什么不大写。
/**
* @param String str The text to be converted to titleCase.
* @param Array glue the words to leave in lowercase.
*/
var titleCase = function(str, glue){
glue = (glue) ? glue : ['of', 'for', 'and'];
return str.replace(/(\w)(\w*)/g, function(_, i, r){
var j = i.toUpperCase() + (r != null ? r : "");
return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
});
};
希望这能帮到你。
edit
如果你想处理领先的粘合词,你可以跟踪这个w/另一个变量:
var titleCase = function(str, glue){
glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
var first = true;
return str.replace(/(\w)(\w*)/g, function(_, i, r) {
var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
first = false;
return result;
});
};
对于我们这些害怕正则表达式的人(lol):
函数标题案例(str) { var words = str.split(“ ”); for ( var i = 0; i < words.length; i++ ) { var j = words[i].charAt(0).toUpperCase(); 单词[i] = j + words[i].substr(1); } 返回 words.join(“ ”); }
它并不短,但这是我最近在学校的一个作业中想到的:
var myPoem = '什么是jQuery,但一个误解的对象?' // jQuery不是被误解的对象吗?JQuery不是一个被误解的对象吗? / /代码 Var大写=函数(str) { var strArr = str.split(' '); var newArr = []; For (var I = 0;i < strar .length;我+ +){ newar .push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1)) }; newArr返回。加入(' ') } var fixedPoem =大写(myPoem); 警报(fixedPoem);
推荐文章
- 我如何使用可选的链接与数组和函数?
- EINVRES请求https://bower.herokuapp.com/packages/失败,提示502
- 使用fetch进行基本身份验证?
- 如何从子组件内部更新React上下文?
- 如何将一个普通对象转换为ES6映射?
- scrollIntoView卷轴太远了
- Angular ng-repeat反过来
- 如何获得请求路径与表达请求对象
- 使用Handlebars 'each'循环访问父对象的属性
- 盎格鲁- ngcloak / ngg展示blink元素
- 禁用表单自动提交按钮单击
- 节点和错误:EMFILE,打开的文件太多
- JavaScript函数中的默认参数值
- 使用RegExp.exec从字符串中提取所有匹配项
- 测试一个值是奇数还是偶数