MDC*_*ore 512 javascript title-case
有没有一种简单的方法将字符串转换为标题案例?我john smith变成了John Smith.我不是在寻找像John Resig这样复杂的解决方案,只是(希望)某种单线或双线.
Gre*_*ean 707
试试这个:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}Run Code Online (Sandbox Code Playgroud)
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>Run Code Online (Sandbox Code Playgroud)
Tua*_*uan 193
一种稍微优雅的方式,适应Greg Dean的功能:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Run Code Online (Sandbox Code Playgroud)
称之为:
"pascal".toProperCase();
Run Code Online (Sandbox Code Playgroud)
小智 161
尝试将文本转换 CSS样式应用于控件.
例如: (text-transform: capitalize);
只在绝对必要时才使用JS方法.
a8m*_*a8m 106
这是我的版本,IMO也很容易理解和优雅.
var str = "foo bar baz"
console.log(
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
)
// returns "Foo Bar Baz"Run Code Online (Sandbox Code Playgroud)
Geo*_*oth 97
这是我的函数,它转换为标题大小写,但也保留定义的首字母缩略词作为大写和小写单词作为小写:
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;
}
Run Code Online (Sandbox Code Playgroud)
例如:
"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:"
Run Code Online (Sandbox Code Playgroud)
Tom*_*Kay 35
我更喜欢以下其他答案.它只匹配每个单词的第一个字母并将其大写.更简单的代码,更易于阅读和更少的字节.它保留现有的大写字母以防止扭曲缩写词.但是你总是可以toLowerCase()先调用你的字符串.
function title(str) {
return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
Run Code Online (Sandbox Code Playgroud)
您可以将其添加到您的字符串原型中,这将允许您'my string'.toTitle()按如下方式:
String.prototype.toTitle = function() {
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
Run Code Online (Sandbox Code Playgroud)
kap*_*dey 20
惊讶地看到没有人提到使用 rest 参数。这是一个使用 ES6 Rest 参数的简单单行代码。
let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)Run Code Online (Sandbox Code Playgroud)
Mik*_*ike 19
不使用正则表达式仅供参考:
String.prototype.toProperCase = function() {
var words = this.split(' ');
var results = [];
for (var i = 0; i < words.length; i++) {
var letter = words[i].charAt(0).toUpperCase();
results.push(letter + words[i].slice(1));
}
return results.join(' ');
};
console.log(
'john smith'.toProperCase()
)Run Code Online (Sandbox Code Playgroud)
fnc*_*omp 16
如果您担心这些填充词,您可以随时告诉函数什么不要大写.
/**
* @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();
});
};
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你.
如果你想处理领先的胶水词,你可以跟踪这个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;
});
};
Run Code Online (Sandbox Code Playgroud)
sim*_*imo 15
这仅适用于一个单词字符串,但这就是我需要的:
var result =
'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())
console.log(result) // This Is Very InterestingRun Code Online (Sandbox Code Playgroud)
JSFiddle: https ://jsfiddle.net/simo/gou2uhLm/
imm*_*han 15
如果上述解决方案中使用的正则表达式让您感到困惑,请尝试以下代码:
function titleCase(str) {
return str.split(' ').map(function(val){
return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
}).join(' ');
}
Run Code Online (Sandbox Code Playgroud)
Uly*_* BN 14
这个基准测试的获胜者是普通的 for 循环:
function titleize(str) {
let upper = true
let newStr = ""
for (let i = 0, l = str.length; i < l; i++) {
// Note that you can also check for all kinds of spaces with
// str[i].match(/\s/)
if (str[i] == " ") {
upper = true
newStr += str[i]
continue
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
upper = false
}
return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.
Run Code Online (Sandbox Code Playgroud)
我采用了最流行和最独特的答案,并以此为基准。
这是我的 MacBook pro 上的结果:
为了完整起见,这里是使用的函数:
str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
function split(str) {
return str.
split(' ').
map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
join(' ');
}
function complete(str) {
var i, j, str, lowers, uppers;
str = str.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;
}
function firstLetterOnly(str) {
return str.replace(/\b(\S)/g, function(t) { return t.toUpperCase(); });
}
function forLoop(str) {
let upper = true;
let newStr = "";
for (let i = 0, l = str.length; i < l; i++) {
if (str[i] == " ") {
upper = true;
newStr += " ";
continue;
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
upper = false;
}
return newStr;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我故意没有更改原型,因为我认为这是一种非常糟糕的做法,我认为我们不应该在我们的答案中推广这种做法。这仅适用于小型代码库,当您是唯一一个处理它的人时。
如果您想在此基准测试中添加任何其他方法,请评论答案的链接!
Kev*_*Bot 12
你可以立即toLowerCase使用字符串,然后只是toUpperCase每个单词的第一个字母.成为一个非常简单的1班轮:
function titleCase(str) {
return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());
}
console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));Run Code Online (Sandbox Code Playgroud)
小智 9
我做了这个功能,可以处理姓氏(所以它不是标题案例),如"麦当劳"或"麦当劳"或"奥图尔"或"D'Orazio".然而,它并不处理带有"van"或"von"的德语或荷兰语名称,这些名称通常是小写的......我认为"de"通常也是小写,例如"Robert de Niro".这些仍然需要解决.
function toProperCase(s)
{
return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
Run Code Online (Sandbox Code Playgroud)
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
return i.toUpperCase() + (r != null ? r : "");
}
)
Run Code Online (Sandbox Code Playgroud)
似乎工作......用上面的测试,"快速的棕色,狐狸?/跳跃/ ^超过'懒惰!狗..."和"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();
});
}
Run Code Online (Sandbox Code Playgroud)
试试这个
String.prototype.toProperCase = function(){
return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g,
function($1){
return $1.toUpperCase();
}
);
};
Run Code Online (Sandbox Code Playgroud)
例
var str = 'john smith';
str.toProperCase();
Run Code Online (Sandbox Code Playgroud)
ES 6
str.split(' ')
.map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
.join(' ')
Run Code Online (Sandbox Code Playgroud)
其他
str.split(' ').map(function (s) {
return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
Run Code Online (Sandbox Code Playgroud)
尝试这个,最短的方式:
str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
Run Code Online (Sandbox Code Playgroud)
首先,将您的string数组按空格拆分:
var words = str.split(' ');
Run Code Online (Sandbox Code Playgroud)
然后使用array.map创建一个包含大写单词的新数组。
var capitalized = words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});
Run Code Online (Sandbox Code Playgroud)
然后用空格加入新数组:
capitalized.join(" ");
Run Code Online (Sandbox Code Playgroud)
var words = str.split(' ');
Run Code Online (Sandbox Code Playgroud)
笔记:
这当然有一个缺点。这只会将每个单词的第一个字母大写。按单词,这意味着它将每个由空格分隔的字符串视为 1 个单词。
假设你有:
str = "I'm a little/small tea pot";
这将产生
我是小/小茶壶
与预期相比
我是小/小茶壶
在这种情况下,使用 Regex 和.replace可以解决问题:
使用 ES6:
var capitalized = words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});
Run Code Online (Sandbox Code Playgroud)
或没有ES6:
capitalized.join(" ");
Run Code Online (Sandbox Code Playgroud)
如果您需要语法正确的答案:
该答案考虑了诸如“of”、“from”、.. 等介词,输出将生成您希望在论文中看到的社论风格标题。
toTitleCase 函数
考虑此处列出的语法规则的函数。该函数还合并空格并删除特殊字符(根据需要修改正则表达式)
const toTitleCase = (str) => {
const articles = ['a', 'an', 'the'];
const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
const prepositions = [
'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
];
// The list of spacial characters can be tweaked here
const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
const normalizeStr = (str) => str.toLowerCase().trim();
const shouldCapitalize = (word, fullWordList, posWithinStr) => {
if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
return true;
}
return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
}
str = replaceCharsWithSpace(str);
str = normalizeStr(str);
let words = str.split(' ');
if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
words = words.map(w => capitalizeFirstLetter(w));
}
else {
for (let i = 0; i < words.length; i++) {
words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
}
}
return words.join(' ');
}
Run Code Online (Sandbox Code Playgroud)
单元测试以确保正确性
import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';
describe('toTitleCase', () => {
it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
});
it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
});
it('Replace special characters with space', function(){
expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
});
it('Trim whitespace at beginning and end', function(){
expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
});
it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
expect(toTitleCase('the three Musketeers And plus ')).to.equal('The Three Musketeers and Plus');
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,我从提供的字符串中删除了相当多的特殊字符。您将需要调整正则表达式以满足项目的要求。
大多数答案似乎忽略了使用单词边界元字符(\ b)的可能性.Greg Dean使用它的简短版本:
function toTitleCase(str)
{
return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}
Run Code Online (Sandbox Code Playgroud)
适用于像Jim-Bob这样的带连字符的名字.
我认为最简单的是使用CSS.
function format_str(str) {
str = str.toLowerCase();
return '<span style="text-transform: capitalize">'+ str +'</span>';
}
Run Code Online (Sandbox Code Playgroud)
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单和简洁的 ES6 函数来做到这一点:
const titleCase = (str) => {
return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}
export default titleCase;
Run Code Online (Sandbox Code Playgroud)
可以很好地包含在utilities文件夹中,并按如下方式使用:
import titleCase from './utilities/titleCase.js';
const string = 'my title & string';
console.log(titleCase(string)); //-> 'My Title & String'
Run Code Online (Sandbox Code Playgroud)
吉姆鲍勃 -> 吉姆鲍勃
\n吉姆/鲍勃 -> 吉姆/鲍勃
\njim_bob -> Jim_Bob
\n不是 -> 不是
\n\xc3\xa9cole -> \xc3\x89cole
\n麦当劳 -> 麦当劳
\nfunction toTitleCase(str) {\n return str.replace(/\\p{L}+('\\p{L}+)?/gu, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.slice(1)\n })\n}\nRun Code Online (Sandbox Code Playgroud)\n
使用/\S+/g支持变音符号:
function toTitleCase(str) {
return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}
console.log(toTitleCase("a city named örebro")); // A City Named ÖrebroRun Code Online (Sandbox Code Playgroud)
然而:" s unshine(y ellow)"⇒" S unshine(y ellow)"
小智 5
这是我的函数,它负责处理重音字符(对于法语很重要!),并且可以打开/关闭对较低异常的处理。希望有帮助。
\n\nString.prototype.titlecase = function(lang, withLowers = false) {\n var i, string, lowers, uppers;\n\n string = this.replace(/([^\\s:\\-'])([^\\s:\\-']*)/g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }).replace(/Mc(.)/g, function(match, next) {\n return 'Mc' + next.toUpperCase();\n });\n\n if (withLowers) {\n if (lang == 'EN') {\n lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];\n }\n else {\n lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', '\xc3\x80', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'O\xc3\xb9', 'Ne', 'Ni', 'Pas'];\n }\n for (i = 0; i < lowers.length; i++) {\n string = string.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), function(txt) {\n return txt.toLowerCase();\n });\n }\n }\n\n uppers = ['Id', 'R&d'];\n for (i = 0; i < uppers.length; i++) {\n string = string.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), uppers[i].toUpperCase());\n }\n\n return string;\n}\nRun Code Online (Sandbox Code Playgroud)\n
如果您可以在代码中使用第三方库,那么lodash为我们提供了一个帮助函数.
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'Run Code Online (Sandbox Code Playgroud)
小智 5
这是使用 css(和 javascript,如果要转换的文本为大写)的另一个解决方案:
html
<span id='text'>JOHN SMITH</span>
Run Code Online (Sandbox Code Playgroud)
js
var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();
Run Code Online (Sandbox Code Playgroud)
CSS
#text{text-transform:capitalize;}
Run Code Online (Sandbox Code Playgroud)
我已经针对土耳其语测试了这个解决方案,它也适用于特殊字符。
\nfunction toTitleCase(str) {\n return str.toLocaleLowerCase().replace(\n /(^|\xc3\x9c|\xc3\xbc|\xc5\x9e|\xc5\x9f|\xc3\x87|\xc3\xa7|\xc4\xb0|\xc4\xb1|\xc3\x96|\xc3\xb6|\\w)\\S*/g,\n (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),\n )\n}\n\nconsole.log(toTitleCase(\'\xc4\xb0SMA\xc4\xb0L HAKKI\'))\nconsole.log(toTitleCase(\'\xc5\x9eAHMARAN B\xc4\xb0NB\xc4\xb0R GECE MASALLARI\'))\nconsole.log(toTitleCase(\'TEKNOLOJ\xc4\xb0 \xc3\x9cR\xc3\x9cN\xc3\x9c\'))Run Code Online (Sandbox Code Playgroud)\r\n由于我已经全部大写数据,因此我在开头添加了“toLocaleLowerCase”。如果不需要,可以将其丢弃。
\n使用区域设置操作对于非英语语言很重要。
\n| 归档时间: |
|
| 查看次数: |
347968 次 |
| 最近记录: |