-
Notifications
You must be signed in to change notification settings - Fork 5
/
romaji-name.js
856 lines (705 loc) · 29.8 KB
/
romaji-name.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
var fs = require("fs");
var enamdict = require("enamdict");
var hepburn = require("hepburn");
var bulkReplace = require("bulk-replace");
// TODO:
// - Move all settings to external settings.json
// - Support string-based formatting of both names and kanji names
// Thanks to Jed Schmidt!
// https://twitter.com/jedschmidt/status/368179809551388672
// https://ja.wikipedia.org/wiki/%E5%A4%A7%E5%AD%97_(%E6%95%B0%E5%AD%97)
var generations = [
/([11一壱壹初](?:代目|代|世|sei|daime)|shodai|\b1\b|\bI(\s|$)|[^0-9]1[^0-9])/ig,
/([22二弐貮貳](?:代目|代|世|sei|daime)|nidaime|\b(?:2|II|ll)\b|Ⅱ|[^0-9]2[^0-9])/ig,
/([33三参參](?:代目|代|世|sei|daime)|sandaime|\b(?:3|III)\b|[^0-9]3[^0-9])/ig,
/([44四肆](?:代目|代|世|sei|daime)|yodaime|\b(?:4|IV)\b|[^0-9]4[^0-9])/ig,
/([55五伍](?:代目|代|世|sei|daime)|godaime|\b(?:5\b|V(\s|$))|[^0-9]5[^0-9])/ig,
/([66六陸](?:代目|代|世|sei|daime)|\b(?:6|VI)\b|[^0-9]6[^0-9])/ig,
/([77七柒漆質](?:代目|代|世|sei|daime)|\b(?:7|VII)\b|[^0-9]7[^0-9])/ig,
/([88八捌](?:代目|代|世|sei|daime)|\b(?:8|VIII)\b|[^0-9]8[^0-9])/ig,
/([99九玖](?:代目|代|世|sei|daime)|\b(?:9|IX)\b|[^0-9]9[^0-9])/ig,
/((?:10|10|[十拾])(?:代目|代|世|sei|daime)|\b(?:10\b|[^0-9]10[^0-9]|X(\s|$)))/ig
];
var generationMap = [ "", "", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"];
// Punctuation
// (Both ASCII and Japanese)
// http://www.localizingjapan.com/blog/2012/01/20/regular-expressions-for-japanese-text/
// Include full width characters?
// Exclude the ' and - marks, they're used in some names
var puncRegex = /[!"#$%&*+,._?\/:;<=>@[\\\]^`{|}~\u3000-\u303F]|(?:^|\s)[\—\-](?:\s|$)/ig;
var aposRegex = /(^|[^nm])'/ig;
// Stop words
var stopRegex = /\b(?:^.*\bby|formerly|et al|can be read|signed|signature|may be translated as|seal|possibly|illustrations|professor|artists other two|born|artist)\b/ig;
// Extract an, at least, 2 character long kanji string
var kanjiRegex = /[\u4e00-\u9faf\u3041-\u3096\u30A0-\u30FF][\u4e00-\u9faf\u3041-\u3096\u30A0-\u30FF\s\d\(\)()々]*[\u4e00-\u9faf\u3041-\u3096\u30A0-\u30FF☆?々](?:\s+[ivxIVX]+\b)?/g;
// Detect unknown artists
var unknownRegex = /unread|unbekannt|no\s+signature|not\s+identified|ansigned|unsigned|numerous|various.*artists|mixed.*artists|anonymous|unknown|unidentified|unidentied|not\s*read|not\s+signed|none|無落款|落款欠|不明|なし/i;
// Detect after
var afterRegex = /\bafter\b|in the style of|of style the in|original|imitator of|fake/i;
// Detect attributed
var attrRegex = /to attributed|attributed to|to atributed|atributed to|attributed|\batt\b/ig;
// Detect school
var schoolRegex = /of school|school of|a pupil of|of pupil a|([\w']+)\s+(?:school|schule|umkreis)/ig;
// Name split
var nameSplitRegex = /\/| with | or | and | & |・/ig;
// Typos and entities to convert
var fixTypos = {
"ʼ": "'",
"shegeharu": "shigeharu",
"kasamastu": "kasamatsu",
"kunimasav": "kunimasa v",
"ktasukawa": "katsukawa",
"katuskawa": "katsukawa",
"kumyiski": "kumyoshi",
"hiroshgie": "hiroshige",
"shunkwaku": "shunkaku",
"yackhyo": "yachiyo"
};
// All the conceivable bad accents that people could use instead of the typical
// Romaji stress mark. The first character in each list has the proper accent.
var letterToAccents = {
'a': 'āâáàăắặấåäǟãą',
'e': 'ēêéèềěëėę',
'i': 'īîíìïį',
'o': 'ōôóòöőõȭȯȱøỏ',
'u': 'ūûúùŭůüųűư'
};
// The formatting for when the full names are generated
var localeFormatting = {
"": "given middle surname generation",
"ja": "surname given generation"
};
// Build up the maps for later replacements
var accentToLetter = {};
var accentToASCII = {};
var accentToGoodAccent = {};
var asciiToAccent = {};
var asciiToLetter = {};
Object.keys(letterToAccents).forEach(function(letter) {
var accents = letterToAccents[letter];
var goodAccent = accents.slice(0, 1);
var letterPair = letter + letter;
accents.split("").forEach(function(accent) {
accentToLetter[accent] = letter;
accentToASCII[accent] = letterPair;
accentToGoodAccent[accent] = goodAccent;
accent = accent.toUpperCase();
accentToLetter[accent] = letter.toUpperCase();
accentToASCII[accent] = letter.toUpperCase() + letter;
accentToGoodAccent[accent] = goodAccent.toUpperCase();
});
// The use of 'ii' is commonly accepted, no accent is used
if (letter !== "i") {
asciiToAccent[letterPair] = goodAccent;
}
// Hack for usage of "ou", treat the same as "oo"
if (letter === "o") {
asciiToAccent["ou"] = goodAccent;
asciiToLetter["ou"] = letter;
}
});
// Cached settings
var defaultSettings = {
fixedNames: {
given: [],
surname: []
}
};
var settings = defaultSettings;
module.exports = {
// Location of the default settings file
settingsFile: __dirname + "/settings.json",
init: function(extraSettings, callback) {
if (arguments.length === 1) {
callback = extraSettings;
extraSettings = defaultSettings;
}
enamdict.init(function() {
this.loadSettings(extraSettings, callback);
}.bind(this));
return this;
},
parseName: function(name, options) {
// Fallback options object
options = options || {};
// Assume that we're re-parsing a name object
if (typeof name === "object") {
if (name.settings) {
for (var prop in name.settings) {
if (!(prop in options)) {
options[prop] = name.settings[prop];
}
}
}
name = name.original || name.name;
}
// Fallback to an empty string if no name is provided
name = name || "";
var nameObj = {
original: name,
locale: "ja"
};
if (Object.keys(options).length > 0) {
nameObj.settings = options;
}
// Simplify the processing by starting in lowercase
var cleaned = name.toLowerCase();
// Fix up the punctuation and whitespace before processing
cleaned = this.cleanWhitespace(cleaned);
cleaned = this.fixTypos(cleaned);
// Optionally remove everything enclosed in parentheses
if (options.stripParens) {
cleaned = this.stripParens(cleaned);
}
// Bail if it's an unknown artist
cleaned = this.extractUnknown(cleaned, nameObj);
// Remove other artists
// TODO: Find a way to expose the other artist names
cleaned = this.stripExtraNames(cleaned);
// Extract extra information (unknown, kanji, generation, etc.)
cleaned = this.extractAfter(cleaned, nameObj);
cleaned = this.extractAttributed(cleaned, nameObj);
cleaned = this.extractSchool(cleaned, nameObj);
cleaned = this.extractGeneration(cleaned, nameObj);
cleaned = this.extractKanji(cleaned, nameObj);
// Clean up the string
cleaned = this.repairName(cleaned);
cleaned = this.stripParens(cleaned);
cleaned = this.flipName(cleaned);
cleaned = this.stripPunctuation(cleaned);
cleaned = this.stripStopWords(cleaned);
// Fix some other things we don't care about
cleaned = cleaned.trim();
var uncorrectedName = cleaned;
// Fix lots of bad Romaji usage
cleaned = this.correctAccents(cleaned);
cleaned = this.stripAccentsToASCII(cleaned);
cleaned = this.correctBadRomaji(cleaned);
// Make sure that ASCII characters are left to convert!
if (/([a-z][a-z'-]*)\s*([a-z' -]*)\s*/.test(cleaned)) {
if (RegExp.$2) {
var surname = RegExp.$1;
var given = RegExp.$2;
} else {
var surname = "";
var given = RegExp.$1;
}
// The kanji represents a different name (alias?)
if (nameObj.differs) {
delete nameObj.kanji;
delete nameObj.given_kanji;
delete nameObj.surname_kanji;
delete nameObj.generation;
}
// Make sure the names are valid romaji before continuing
if ((surname && !this.toKana(surname) && surname.length > 1) ||
(given && !this.toKana(given) && given.length > 1)) {
// If one of them is not valid then we assume that we're
// dealing with a western name so we just leave it as-is.
var parts = uncorrectedName.split(/\s+/);
nameObj.locale = "";
nameObj.given = parts[0];
nameObj.surname = "";
if (parts.length === 2) {
nameObj.surname = parts[1];
} else if (parts.length > 2) {
var middle = parts.slice(1, parts.length - 1);
nameObj.middle = middle.map(function(name) {
return name.length === 1 ? name + "." : name;
}).join(" ");
if (nameObj.middle.toLowerCase() === "no") {
delete nameObj.middle;
}
nameObj.surname = parts[parts.length - 1];
} else if (parts.length === 1) {
// If only one name is provided then it's likely the
// surname, which is more common in non-Japanese locales.
nameObj.surname = nameObj.given;
nameObj.given = "";
}
if (options.flipNonJa && nameObj.surname) {
var tmp = nameObj.given;
nameObj.given = nameObj.surname;
nameObj.surname = tmp;
}
// Use the built-in name fixes as a first list of defense
if (settings.fixedNames.given.indexOf((nameObj.surname || "").toLowerCase()) >= 0 ||
settings.fixedNames.surname.indexOf(nameObj.given.toLowerCase()) >= 0) {
var tmp = nameObj.given;
nameObj.given = nameObj.surname;
nameObj.surname = tmp;
}
this.injectFullName(nameObj);
return nameObj;
} else {
var parts = given.split(/\s+/);
if (parts.length > 1) {
var middle = parts.slice(0, parts.length - 1);
nameObj.middle = middle.join(" ");
if (nameObj.middle.toLowerCase() === "no") {
delete nameObj.middle;
}
given = parts[parts.length - 1];
}
}
// If givenFirst is specified then we assume that the given
// name is always first. This doesn't matter for non-Japanese
// names (like above) but does matter for Japanese names,
// which are expected to be surname first.
if (options.givenFirst && surname && given) {
var tmp = surname;
surname = given;
given = tmp;
// Use the built-in name fixes as a first list of defense
} else if (settings.fixedNames.given.indexOf(surname) >= 0 ||
settings.fixedNames.surname.indexOf(given) >= 0) {
var tmp = given;
given = surname;
surname = tmp;
}
var allowSwap = settings.fixedNames.given.indexOf(given) < 0 &&
settings.fixedNames.surname.indexOf(surname) < 0;
// Look up the two parts of the name in ENAMDICT
var givenEntries = enamdict.find(given);
var surnameEntries = enamdict.find(surname);
if (nameObj.given_kanji || nameObj.surname_kanji) {
allowSwap = false;
// Assume that the Kanji version of the name is in the right
// order. Make sure that the romaji name matches the Kanji.
if (given && surname &&
(givenEntries &&
givenEntries.kanji().indexOf(nameObj.surname_kanji) >= 0 ||
surnameEntries &&
surnameEntries.kanji().indexOf(nameObj.given_kanji) >= 0)) {
var tmp = surnameEntries;
surnameEntries = givenEntries;
givenEntries = tmp;
tmp = surname;
surname = given;
given = tmp;
}
}
if (given && surname && (givenEntries || surnameEntries)) {
// Fix cases where only one of the two names was found
if (allowSwap && (!givenEntries || !surnameEntries)) {
if (givenEntries) {
// Swap the names if they're in the wrong place
if (givenEntries.type() === "surname") {
var tmp = surname;
surname = given;
given = tmp;
surnameEntries = givenEntries;
givenEntries = null;
}
} else {
// Swap the names if they're in the wrong place
if (surnameEntries.type() === "given") {
var tmp = given;
given = surname;
surname = tmp;
givenEntries = surnameEntries;
surnameEntries = null;
}
}
// Otherwise both parts of the name were found
// Fix the case where the names are reversed
} else if (allowSwap && (surnameEntries.type() === "given" ||
givenEntries.type() === "surname") &&
surnameEntries.type() !== givenEntries.type()) {
var tmp = surnameEntries;
surnameEntries = givenEntries;
givenEntries = tmp;
}
// Get the romaji names, if they exist in ENAMDICT
// If not, fall back to what was provided
var givenRomaji = this.correctBadRomaji(givenEntries ?
givenEntries.romaji() : given);
var surnameRomaji = this.correctBadRomaji(surnameEntries ?
surnameEntries.romaji() : surname);
// Generate our own kana using hepburn
var givenKana = this.toKana(givenRomaji || "");
var surnameKana = this.toKana(surnameRomaji || "");
if (givenRomaji) {
nameObj.given = this.convertRepeatedVowel(givenRomaji);
nameObj.given_kana = givenKana;
}
if (surnameRomaji) {
nameObj.surname = this.convertRepeatedVowel(surnameRomaji);
nameObj.surname_kana = surnameKana;
}
this.splitKanjiByName(nameObj, givenEntries, surnameEntries);
this.injectFullName(nameObj);
} else {
if (surname) {
nameObj.surname = this.convertRepeatedVowel(surname);
nameObj.surname_kana = this.toKana(surname);
}
nameObj.given = this.convertRepeatedVowel(given);
nameObj.given_kana = this.toKana(given);
this.splitKanjiByName(nameObj, givenEntries);
this.injectFullName(nameObj);
}
// Otherwise there was only kanji left and we haven't already
// detected which characters belong to the surname or given name
} else if (nameObj.kanji && !nameObj.given_kanji) {
this.splitKanji(nameObj);
this.injectFullName(nameObj);
// Otherwise we need to build the full kanji from the parts
} else if (nameObj.given_kanji) {
this.injectFullName(nameObj);
}
// Handle when there's no parseable name
if (!nameObj.name && !nameObj.given && !nameObj.surname &&
!nameObj.kanji) {
nameObj.unknown = true;
}
delete nameObj.differs;
return nameObj;
},
loadSettings: function(extraSettings, callback) {
fs.readFile(this.settingsFile, function(err, data) {
settings = JSON.parse(data.toString("utf8"));
callback();
});
},
splitKanjiByName: function(nameObj, givenEntries, surnameEntries) {
// Figure out how the kanji name relates to which name part
if (!nameObj.kanji || nameObj.given_kanji) {
return;
}
var nameKanji = nameObj.kanji;
var givenKanji = givenEntries && givenEntries.kanji();
var surnameKanji = surnameEntries &&
surnameEntries.kanji();
if (!givenKanji && !surnameKanji) {
this.splitKanji(nameObj);
return;
}
if (givenKanji) {
var foundNames = givenKanji.filter(function(kanji) {
return nameKanji.indexOf(kanji) >= 0;
});
// Hopefully only one name is found
if (foundNames.length > 0) {
nameObj.given_kanji = foundNames[0];
}
}
if (surnameKanji) {
var foundNames = surnameKanji.filter(function(kanji) {
return nameKanji.indexOf(kanji) >= 0;
});
// Hopefully only one name is found
if (foundNames.length > 0) {
nameObj.surname_kanji = foundNames[0];
}
}
// If only one of the kanji is found
if (nameObj.given_kanji !== nameObj.surname_kanji) {
if (nameObj.given_kanji &&
nameObj.given_kanji !== nameKanji) {
nameObj.surname_kanji = nameKanji
.replace(nameObj.given_kanji, "");
} else if (nameObj.surname_kanji &&
nameObj.surname_kanji !== nameKanji) {
nameObj.given_kanji = nameKanji
.replace(nameObj.surname_kanji, "");
}
}
},
splitKanji: function(nameObj) {
if (nameObj.kanji.length <= 2) {
// If it's very short then it's probably not a full
// name, just the given name.
nameObj.given_kanji = nameObj.kanji;
} else if (nameObj.kanji.length <= 3 &&
enamdict.findKanji(nameObj.kanji)) {
// Assume that if we have an exact match that it's
// a valid given name (the surname, alone, is almost never
// specified).
nameObj.given_kanji = nameObj.kanji;
} else if (nameObj.kanji.length === 4) {
// Almost always a name of length 4 means that there is
// a surname of length 2 and a given name of length 2
nameObj.surname_kanji = nameObj.kanji.substr(0, 2);
nameObj.given_kanji = nameObj.kanji.substr(2);
} else {
// For everything else we need to slice-and-dice the
// name to make sure that we have the correct name parts
var complete = [];
var partial = [];
// Split name 1 .. n
for (var pos = 2; pos < nameObj.kanji.length - 1; pos++) {
var surname = nameObj.kanji.substr(0, pos);
var given = nameObj.kanji.substr(pos);
var match = {
diff: Math.abs(surname.length - given.length),
surname: enamdict.findKanji(surname),
given: enamdict.findKanji(given)
};
if (match.surname && match.given) {
complete.push(match);
} else if (match.surname || match.given) {
partial.push(match);
}
}
if (complete.length > 0) {
// Find the name with the least-dramatic difference in
// size (e.g. AABB is more likely than ABBB)
complete = complete.sort(function(a, b) {
return Math.abs(a.surname.length - a.given.length) -
Math.abs(b.surname.length - b.given.length);
});
nameObj.surname_kanji = complete[0].surname.kanji();
nameObj.given_kanji = complete[0].given.kanji();
// Otherwise if there are an odd number of partial matches then
// we guess and go for the one that evenly splits the name
} else if (partial.length > 0) {
partial = partial.filter(function(name) {
return name.diff === 0;
});
if (partial.length > 0) {
var partialSurname = partial[0].surname &&
partial[0].surname.kanji();
var partialGiven = partial[0].given &&
partial[0].given.kanji();
if (partialSurname) {
partialGiven = nameObj.kanji
.replace(partialSurname, "");
} else {
partialSurname = nameObj.kanji
.replace(partialGiven, "");
}
nameObj.surname_kanji = partialSurname;
nameObj.given_kanji = partialGiven;
}
}
// Anything else is going to be too ambiguous
}
},
genFullName: function(nameObj) {
var name = "";
var formatting = localeFormatting[nameObj.locale] || "";
formatting.split(/\s+/).forEach(function(part) {
var value = nameObj[part];
if (part === "generation") {
value = generationMap[value];
}
// Only add something if the part is empty and don't add
// a generation if it's just 1 (since it's superflous)
if (value) {
name += (name ? " " : "") + value;
}
});
return name.trim();
},
injectFullName: function(nameObj) {
this.capitalizeNames(nameObj);
var name = this.genFullName(nameObj);
if ((nameObj.locale === "ja" ? nameObj.given : nameObj.surname) && name) {
nameObj.name = name;
if (nameObj.locale === "ja") {
nameObj.ascii = this.genFullName({
locale: nameObj.locale,
given: this.stripAccentsToASCII(nameObj.given || ""),
surname: this.stripAccentsToASCII(nameObj.surname || ""),
middle: this.stripAccentsToASCII(nameObj.middle || ""),
generation: nameObj.generation
});
} else {
nameObj.ascii = nameObj.name;
}
nameObj.plain = this.genFullName({
locale: nameObj.locale,
given: this.stripAccents(nameObj.given || ""),
surname: this.stripAccents(nameObj.surname || ""),
middle: this.stripAccents(nameObj.middle || ""),
generation: nameObj.generation
});
}
if (nameObj.given_kana) {
nameObj.kana = (nameObj.surname_kana || "") + nameObj.given_kana;
}
var kanjiGeneration = (nameObj.generation ?
" " + nameObj.generation + "世" : "");
if (nameObj.given_kanji) {
nameObj.kanji = (nameObj.surname_kanji ?
nameObj.surname_kanji : "") +
nameObj.given_kanji + kanjiGeneration;
} else if (nameObj.kanji) {
nameObj.kanji += kanjiGeneration;
}
return nameObj;
},
capitalizeNames: function(nameObj) {
if (nameObj.given) {
nameObj.given = this.capitalize(nameObj.given);
}
if (nameObj.middle) {
nameObj.middle = this.capitalize(nameObj.middle);
}
if (nameObj.surname) {
nameObj.surname = this.capitalize(nameObj.surname);
}
},
capitalize: function(name) {
return name.toLowerCase().replace(/(?:^|\s)./g, function(all) {
return all.toUpperCase();
});
},
cleanWhitespace: function(name) {
return name.replace(/\r?\n/g, " ").trim();
},
fixTypos: function(name) {
return bulkReplace(name, fixTypos);
},
flipName: function(name, split) {
split = split || /,\s*/;
return name.split(split).reverse().join(" ");
},
repairName: function(name) {
// Placeholder characters that will be replaced in a name
// This almost always happens on poorly formatted web sites.
name = name.replace(/([aeiou])_/g, "$1$1");
// This is definitely a hack but it seems to be the case
// for many of these particular problems.
return name.replace(/[?_]/g, "o");
},
stripStopWords: function(name) {
return name.replace(stopRegex, "");
},
stripExtraNames: function(name) {
return name.split(nameSplitRegex)[0];
},
stripPunctuation: function(name) {
return name
.replace(puncRegex, " ")
.replace(aposRegex, function(all, before) {
return before;
}).trim();
},
stripAccents: function(name) {
return bulkReplace(name, accentToLetter);
},
stripAccentsToASCII: function(name) {
return bulkReplace(name, accentToASCII);
},
correctAccents: function(name) {
return bulkReplace(name, accentToGoodAccent);
},
correctBadRomaji: function(name) {
return hepburn.cleanRomaji(name).toLowerCase();
},
convertRepeatedVowel: function(name) {
return bulkReplace(name, asciiToAccent);
},
stripParens: function(name) {
// Start by removing parens and the contents inside of them
return name.replace(/\s*[\((][^\))]*[\))]\s*/g, " ")
// Strip any remaining parens separately
.replace(/[\((\))]/g, "");
},
extractAttributed: function(name, nameObj) {
name = name.replace(attrRegex, function(all) {
nameObj.attributed = true;
return "";
});
return name;
},
extractAfter: function(name, nameObj) {
name = name.replace(afterRegex, function(all) {
nameObj.after = true;
return "";
});
return name;
},
extractSchool: function(name, nameObj) {
var self = this;
name = name.replace(schoolRegex, function(all) {
nameObj.school = true;
if (RegExp.$1) {
name = "";
nameObj.surname = RegExp.$1;
self.injectFullName(nameObj);
}
return "";
});
return name;
},
extractUnknown: function(name, nameObj) {
if (unknownRegex.test(name)) {
name = "";
nameObj.unknown = true;
nameObj.locale = "";
}
return name;
},
fixRepeatedKanji: function(name) {
return name.replace(/(.)々/g, "$1$1");
},
extractKanji: function(name, nameObj) {
var self = this;
var kanji = "";
name = name.replace(kanjiRegex, function(all) {
if (!kanji) {
kanji = self.stripParens(self.stripPunctuation(
self.fixRepeatedKanji(all))).trim();
}
return "";
});
if (kanji) {
// Extract generation info from kanji if it exists
kanji = this.extractGeneration(kanji, nameObj).trim();
// Strip extraneous whitespace from the kanji
kanji = kanji.replace(/\s+/g, " ").trim();
var parts = kanji.split(/\s+/);
// Surname and given name are already specified
if (parts.length === 2) {
// Handle case where there are multiple space-separated names
if (parts[0].length >= 4 && parts[1].length >= 4) {
kanji = parts[0];
nameObj.kanji = kanji;
} else {
nameObj.surname_kanji = parts[0];
nameObj.given_kanji = parts[1];
}
} else {
nameObj.kanji = kanji;
}
}
return name;
},
extractGeneration: function(name, nameObj) {
var generation;
// Don't look for the generation inside parens
var trimName = this.stripParens(name);
generations.forEach(function(genRegex, i) {
if (!generation && genRegex.test(trimName)) {
generation = i + 1;
// Handle the case where the name is written:
// Given Generation Surname
var invertedName = new RegExp("([a-z'-]+)\\s+" + RegExp.$1 +
"\\s+([a-z'-]+)", "i");
if (invertedName.test(name)) {
name = name.replace(invertedName, "$2 $1");
} else {
name = name.replace(genRegex, function(all, name, extra) {
return typeof extra === "string" && extra || "";
});
}
}
});
// Specifying 1st generation is redundant
if (generation === 1) {
generation = undefined;
}
if (generation) {
nameObj.generation = generation;
}
return name;
},
toKana: function(name) {
// TODO: Should oo -> ou to match the conventions of ENAMDICT?
var ret = hepburn.toHiragana(name.replace(/-/g, ""));
return /[a-z]/i.test(ret) ? "" : ret;
}
};