是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
我用正则表达式回答。
更多regex信息:https://regex101.com/r/AgRM3p/1
function toTitleCase(string = '') { const regex = /^[a-z]{0,1}|\s\w/gi; string = string.toLowerCase(); string.match(regex).forEach((char) => { string = string.replace(char, char.toUpperCase()); }); return string; } const input = document.getElementById('fullname'); const button = document.getElementById('button'); const result = document.getElementById('result'); button.addEventListener('click', () => { result.innerText = toTitleCase(input.value); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> </head> <body> <input type="text" id="fullname"> <button id="button">click me</button> <p id="result">Result here</p> <script src="./index.js"></script> </body> </html>
其他回答
如果一个CSS解决方案满足你的需求,你可以应用文本转换CSS样式到你的控件:
text-transform: capitalize;
请注意,这将会改变: hello world到hello world HELLO WORLD到HELLO WORLD(不变) emily-jane o'brien致emily-jane o'brien(不正确) 玛丽亚·冯·特拉普写给玛丽亚·冯·特拉普(不正确)
这个解决方案将标点符号考虑到新句子中,处理引用,将小词转换为小写,忽略首字母缩写或全大写单词。
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. */
Var结果= “这很有趣”。/\b[a-z]/g, (x) => x. touppercase ()) console.log(result) // This Is Very Interesting
实现类似功能的另一种方法如下所示。
formatName(name) {
let nam = '';
name.split(' ').map((word, index) => {
if (index === 0) {
nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
} else {
nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
}
});
return nam;
}
更简单的高性能版本,具有简单的缓存。
var TITLE_CASE_LOWER_MAP = { 'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1, 'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1 }; // LEAK/CACHE TODO: evaluate using LRU. var TITLE_CASE_CACHE = new Object(); toTitleCase: function (title) { if (!title) return null; var result = TITLE_CASE_CACHE[title]; if (result) { return result; } result = ""; var split = title.toLowerCase().split(" "); for (var i=0; i < split.length; i++) { if (i > 0) { result += " "; } var word = split[i]; if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) { word = word.substr(0,1).toUpperCase() + word.substr(1); } result += word; } TITLE_CASE_CACHE[title] = result; return result; },
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔