Convert string to title case with JavaScript
是否有一种简单的方法可以将字符串转换为标题大小写?例如,
试试这个:
1 2 3 4 5 6 7 8 | function toTitleCase(str) { return str.replace( /\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); } |
1 2 3 4 5 6 | <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> |
稍微优雅一点的方式,调整格雷格·迪恩的功能:
1 2 3 | String.prototype.toProperCase = function () { return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }; |
称之为:
1 | "pascal".toProperCase(); |
尝试将文本转换CSS样式应用于控件。
例如:
只有在绝对必要时才使用JS方法。
下面是我的函数,它转换为标题大小写,但也将定义的首字母缩略词保留为大写,将副词保留为小写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |
例如:
1 2 | "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:" |
这是我的版本,我觉得它也很容易理解和优雅。
1 2 3 4 5 6 7 | var str ="foo bar baz" str.split(' ') .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()) .join(' ') // returns"Foo Bar Baz" |
我比较喜欢下面的答案。它只匹配每个单词的第一个字母,并将其大写。代码更简单,更容易读取,字节更少。它保留了现有的大写字母,以防止缩写词失真。但是,您总是可以先在字符串上调用
1 2 3 | function title(str) { return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() }); } |
您可以将其添加到字符串原型中,这样您就可以按如下方式使用
1 2 3 | String.prototype.toTitle = function() { return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() }); } |
不使用regex作为参考:
1 2 3 4 5 6 7 8 9 10 11 | 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(' '); }; 'john smith'.toProperCase(); |
为了防止你担心这些填充词,你可以告诉函数什么不是大写。
1 2 3 4 5 6 7 8 9 10 11 | /** * @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(); }); }; |
希望这能帮到你。
编辑如果要处理前导的粘合词,可以跟踪此w/另一个变量:
1 2 3 4 5 6 7 8 9 10 | 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; }); }; |
如果上述解决方案中使用的regex使您感到困惑,请尝试以下代码:
1 2 3 4 5 | function titleCase(str) { return str.split(' ').map(function(val){ return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase(); }).join(' '); } |
这只适用于一个单词串,但这正是我需要的:
1 | 'string'.replace(/^[a-z]/, function (x) {return x.toUpperCase()}) // String |
jfiddle:https://jsfiddle.net/simo/gou2uhlm/
你可以立即用
1 2 3 4 5 6 | function titleCase(str) { return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase()); } console.log(titleCase('iron man')); console.log(titleCase('iNcrEdible hulK')); |
我做了这个函数,可以处理姓氏(所以不是标题),比如"麦当劳"、"麦克唐纳"、"O'toole"或"D'orazio"。但是它不处理带有"van"或"von"的德语或荷兰语名称,后者通常是小写…我认为"de"通常也是小写的,比如"robert de niro"。这些问题仍然需要解决。
1 2 3 4 5 | 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(); }); } |
ES 6
1 2 3 | str.split(' ') .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase()) .join(' ') |
其他的
1 2 3 | str.split(' ').map(function (s) { return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase(); }).join(' ') |
1 2 3 4 5 | var toMatch ="john w. smith"; var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) { return i.toUpperCase() + (r != null ? r :""); } ) |
似乎有效…上面的测试,"快速棕色,狐狸?/跳过/跳过^懒惰!dog…"和"c:/program files/some vendor/their 2nd application/a file1.txt"。
如果你想要第二个而不是第二个,你可以改为
第一种形式可以简化为:
1 2 3 4 5 | function toTitleCase(toTransform) { return toTransform.replace(/\b([a-z])/g, function (_, initial) { return initial.toUpperCase(); }); } |
试试这个,最短的方法:
1 | str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase()); |
试试这个
1 2 3 4 5 6 7 | String.prototype.toProperCase = function(){ return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, function($1){ return $1.toUpperCase(); } ); }; |
例子
1 2 | var str = 'john smith'; str.toProperCase(); |
大多数答案似乎忽略了使用单词boundary元字符()的可能性。格雷格·迪恩的答案的较短版本:
1 2 3 4 | function toTitleCase(str) { return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); }); } |
也适用于像JimBob这样的连字符名称。
我认为最简单的方法是使用CSS。
1 2 3 4 | function format_str(str) { str = str.toLowerCase(); return '<span style="text-transform: capitalize">'+ str +'</span>'; } |
如果您可以在代码中使用第三方库,那么lodash为我们提供了一个助手函数。
https://lodash.com/docs/4.17.3启动案例
1 2 3 4 5 6 7 8 9 10 11 | _.startCase('foo bar'); // => 'Foo Bar' _.startCase('--foo-bar--'); // => 'Foo Bar' _.startCase('fooBar'); // => 'Foo Bar' _.startCase('__FOO_BAR__'); // => 'FOO BAR' |
使用
1 2 3 4 5 | 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 ?rebro |
然而:"阳光(黄色)"?阳光(黄色)
以"lewax00"解决方案为例,我创建了一个简单的解决方案,强制从空格开始的"w"或启动de-word的"w",但无法删除额外的中间空格。
1 | "SOFíA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); }); |
结果是"Sof_a Vergara"。
对于害怕正则表达式的人(lol):
1 2 3 4 5 6 7 8 9 10 | function titleCase(str) { var words = str.split(""); for ( var i = 0; i < words.length; i++ ) { var j = words[i].charAt(0).toUpperCase(); words[i] = j + words[i].substr(1); } return words.join(""); } |
我想添加我自己的答案,因为我需要一个健壮的
该函数还合并空白并删除特殊字符(根据需要修改regex)
总酶功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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(' '); } |
确保正确性的单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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'); }); }); |
请注意,我正在从提供的字符串中删除相当多的特殊字符。您需要调整regex以满足项目的需求。
我们已经在办公室进行了讨论,我们认为,试图自动更正人们按您希望的方式输入姓名的方式,这可能会带来很多问题。
我们已经提出了几种不同类型的自动大写字母分离的情况,这些情况仅适用于英文名称,每种语言都有其自身的复杂性。
每个名字首字母大写的问题:
?像ibm这样的缩写词不允许输入,就会变成ibm。
?麦当劳这个名字会变成麦当劳,这是不正确的,同样是麦当劳。
?像玛丽·唐克斯这样的双管姓会变成玛丽·唐克斯。
?像奥康纳这样的名字会变成奥康纳。
对于其中的大多数,您可以编写自定义规则来处理它,但是,这仍然与以前一样存在首字母缩略词问题,并且您会遇到一个新问题:
?加入一个规则来修正Mac的名字,比如MacDonald,这会使诸如Macy这样的破名变成Macy。
我们提出的唯一一个解决方案是将每个字母大写,这是DBS似乎也使用的一种暴力方法。
因此,如果你想自动化这一过程,如果没有一本每一个名字和单词的字典,以及如何对其进行资本化处理,就不可能做到这一点。如果你没有涵盖所有内容的规则,就不要使用它,因为它只会让你的用户感到恼火,并提示那些想正确输入名字的人去其他地方。
这里是我的函数,它处理重音字符(对法语很重要!)这可以打开/关闭对降低异常的处理。希望有帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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; } |
这是基于我对FreeCodeCamp的BonFire"标题大小写"的解决方案,它要求您首先将给定的字符串转换为所有小写,然后将处理空格的每个字符转换为大写。
不使用regex:
1 2 3 | function titleCase(str) { return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' '); } |
下面是另一个使用css(和javascript的解决方案,如果要转换的文本是大写的):
HTML
1 | <span id='text'>JOHN SMITH</span> |
JS
1 2 | var str = document.getElementById('text').innerHtml; var return_text = str.toLowerCase(); |
CSS
1 | #text{text-transform:capitalize;} |
我简单易懂的版本:
1 2 3 4 5 6 7 8 9 10 | function titlecase(str){ var arr=[]; var str1=str.split(' '); for (var i = 0; i < str1.length; i++) { var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1); arr.push(upper); }; return arr.join(' '); } titlecase('my name is suryatapa roy'); |
首先,将您的
1 | var words = str.split(' '); |
然后使用array.map创建包含大写单词的新数组。
1 2 3 | var capitalized = words.map(function(word) { return word.charAt(0).toUpperCase() + word.substring(1, word.length); }); |
然后用空格连接新数组:
1 | capitalized.join(""); |
1 2 3 4 5 6 7 8 9 10 11 | function titleCase(str) { str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end var words = str.split(""); var capitalized = words.map(function(word) { return word.charAt(0).toUpperCase() + word.substring(1, word.length); }); return capitalized.join(""); } console.log(titleCase("I'm a little tea pot")); |
注:
这当然有缺点。这只会将每个单词的第一个字母大写。换句话说,这意味着它将分隔我的空格的每个字符串视为1个单词。
假设你有:
这将产生
I'm A Little/small Tea Pot
与预期相比
I'm A Little/small Tea Pot
在这种情况下,使用regex和.replace将实现以下功能:
用ES6:
1 2 3 4 5 6 7 8 9 10 11 12 | const capitalize = str => str.length ? str[0].toUpperCase() + str.slice(1).toLowerCase() : ''; const escape = str => str.replace(/./g, c => `\\${c}`); const titleCase = (sentence, seps = ' _-/') => { let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g'); return sentence.replace(wordPattern, capitalize); }; console.log( titleCase("I'm a little/small tea pot.") ); |
或没有ES6:
1 2 3 4 5 6 7 8 9 | function capitalize(str) { return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase(); } function titleCase(str) { return str.replace(/[^\ \/\-\_]+/g, capitalize); } console.log(titleCase("hello/hi world")); |
下面是一个简单的问题解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function Title_Case(phrase) { var revised = phrase.charAt(0).toUpperCase(); for ( var i = 1; i < phrase.length; i++ ) { if (phrase.charAt(i - 1) =="") { revised += phrase.charAt(i).toUpperCase(); } else { revised += phrase.charAt(i).toLowerCase(); } } return revised; } |
更简单更高性能的版本,具有简单的缓存。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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; }, |
格雷格·迪恩解的原型解:
1 2 3 | String.prototype.capitalize = function() { return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | function capitalize(str) { const word = []; for (let char of str.split(' ')) { word.push(char[0].toUpperCase() + char.slice(1)) } return word.join(' '); } console.log(capitalize("this is a test")); |
这不短,但我最近在学校的一个任务是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var myPoem = 'What is a jQuery but a misunderstood object?' //What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object? //code here var capitalize = function(str) { var strArr = str.split(' '); var newArr = []; for (var i = 0; i < strArr.length; i++) { newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1)) }; return newArr.join(' ') } var fixedPoem = capitalize(myPoem); alert(fixedPoem); |
做
外宣版
1 2 3 4 5 6 7 8 9 10 11 | 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 } |
实施版本
1 2 3 4 5 6 7 8 | function toTitleCase(input){ return input .split(' ') .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()) .join(' ') } toTitleCase('HoW ARe yoU') // reuturn 'How Are You' |
有一些很好的答案,但是,很多人使用regex来查找单词,但是,出于某种原因,没有人使用regex来替换第一个字符。为了便于解释,我将提供一个长的解决方案和一个短的解决方案。
长期解决方案(更具解释性)。通过使用正则表达式
1 2 3 4 5 | function toUpperCase(str) { return str.toUpperCase(); } function capitalizeWord(word) { return word.replace(/./, toUpperCase); } function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); } console.log(capitalize("hello world")); // Outputs: Hello World |
对于执行相同操作的单个函数,我们嵌套
1 2 3 4 5 6 7 | function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) { return word.replace(/./, function (ch) { return ch.toUpperCase(); } ); } ); } console.log(capitalize("hello world")); // Outputs: Hello World |
像约翰·雷西格的解决方案一样功能齐全,但作为一个一行程序:(基于这个Github项目)
1 2 3 | function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})}; console.log( toTitleCase("ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ES-6 way to get title case of a word or entire line. ex. input = 'hEllo' --> result = 'Hello' ex. input = 'heLLo woRLd' --> result = 'Hello World' const getTitleCase = (str) => { if(str.toLowerCase().indexOf(' ') > 0) { return str.toLowerCase().split(' ').map((word) => { return word.replace(word[0], word[0].toUpperCase()); }).join(' '); } else { return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase(); } } |
实现类似目标的另一种方法如下。
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
一种使用reduce的方法
1 2 3 4 5 6 7 8 | function titleCase(str) { const arr = str.split(""); const result = arr.reduce((acc, cur) => { const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase(); return acc += `${newStr} ` },"") return result.slice(0, result.length-1); } |
这个解决方案将标点符号考虑到新的句子中,处理引用,将小词转换为小写,忽略首字母缩略词或所有大写词。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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. */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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"); |
这是一行解决方案,如果要转换字符串中的每个工作,请将字符串拆分为"",迭代这些部分并将此解决方案应用于每个部分,将每个转换的部分添加到一个数组中并使用""将其联接。
1 2 3 | var stringToConvert = 'john'; stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join(''); console.log(stringToConvert); |
约翰·史密斯->约翰·史密斯
1 | 'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function titleCase(str) { str = str.toLowerCase(); var strArray = str.split(""); for(var i = 0; i < strArray.length; i++){ strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1); } var result = strArray.join(""); //Return the string return result; } |
1 2 3 4 5 6 | String.prototype.capitalize = function() { return this.toLowerCase().split(' ').map(capFirst).join(' '); function capFirst(str) { return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1); } } |
用途:
1 | "hello world".capitalize() |
只是另一个版本添加到混合中。这还将检查string.length是否为0:
1 2 3 4 5 6 7 8 9 10 11 | String.prototype.toTitleCase = function() { var str = this; if(!str.length) { return""; } str = str.split(""); for(var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : ''); } return (str.length ? str.join("") : str); }; |
https://lodash.com/docs/4.17.11大写
使用Lodash库….!更可靠
1 | _.capitalize('FRED'); => 'Fred' |
ES6单衬套
1 | const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' '); |