1+ /*Copyright © 2008–2018 David Gouch
2+
3+ Permission is hereby granted, free of charge, to any person obtaining a copy
4+ of this software and associated documentation files (the "Software"), to deal
5+ in the Software without restriction, including without limitation the rights
6+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+ copies of the Software, and to permit persons to whom the Software is
8+ furnished to do so, subject to the following conditions:
9+
10+ The above copyright notice and this permission notice shall be included in
11+ all copies or substantial portions of the Software.
12+
13+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+ THE SOFTWARE.
20+ */
21+
22+ export default function toTitleCase ( s ) {
23+ var smallWords = / ^ ( a | a n | a n d | a s | a t | b u t | b y | e n | f o r | i f | i n | n o r | o f | o n | o r | p e r | t h e | t o | v .? | v s .? | v i a ) $ / i
24+ var alphanumericPattern = / ( [ A - Z a - z 0 - 9 \u00C0 - \u00FF ] ) /
25+ var wordSeparators = / ( [ : – — - ] ) /
26+
27+ return s . split ( wordSeparators )
28+ . map ( function ( current , index , array ) {
29+ if (
30+ /* Check for small words */
31+ current . search ( smallWords ) > - 1 &&
32+ /* Skip first and last word */
33+ index !== 0 &&
34+ index !== array . length - 1 &&
35+ /* Ignore title end and subtitle start */
36+ array [ index - 3 ] !== ':' &&
37+ array [ index + 1 ] !== ':' &&
38+ /* Ignore small words that start a hyphenated phrase */
39+ ( array [ index + 1 ] !== '-' ||
40+ ( array [ index - 1 ] === '-' && array [ index + 1 ] === '-' ) )
41+ ) {
42+ return current . toLowerCase ( )
43+ }
44+
45+ /* Ignore intentional capitalization */
46+ if ( current . substr ( 1 ) . search ( / [ A - Z ] | \. ./ ) > - 1 ) {
47+ return current
48+ }
49+
50+ /* Ignore URLs */
51+ if ( array [ index + 1 ] === ':' && array [ index + 2 ] !== '' ) {
52+ return current
53+ }
54+
55+ /* Capitalize the first letter */
56+ return current . replace ( alphanumericPattern , function ( match ) {
57+ return match . toUpperCase ( )
58+ } )
59+ } )
60+ . join ( '' )
61+ }
0 commit comments