-
Notifications
You must be signed in to change notification settings - Fork 1
/
lacinka.js
79 lines (63 loc) · 2.29 KB
/
lacinka.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
const cyrillicAlphabet = ['а', 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'н', 'ў', 'ф', 'х', 'ц', 'ч', 'ш', 'ы', 'ь', 'э'];
const latinVersion = ['a', 'b', 'v', 'h', 'd', 'ž', 'z', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'n', 'ǔ', 'f', 'ch', 'c', 'č', 'š', 'y', '@', 'e'];
const softVowelsCyrillic = [ 'е', 'ё', 'і', 'ю', 'я'];
const softVowelsLatin = [ 'je', 'jo', 'i', 'ju', 'ja'];
const latinAdition = [ 'ł', 'ń', 'ś', 'š', 'dz', 'dź','dž', 'ź']
class Lacinka {
constructor() {
this.specialSymbolPattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,./{}|\\":<>\?]/);
this.latinPattern = new RegExp(/[A-z\u00C0-\u00ff]+/g);
this.cyrillicPattern = new RegExp(/[\u0400-\u04FF]/);
let textNodes = this.getTextNodes();
textNodes.forEach((textNode, i) => {
textNode.nodeValue = this.latinizeStr(textNode.textContent);
});
}
latinizeStr(cyrillicStr) {
console.log(cyrillicStr);
let latinStr = '';
for (let i = 0; i < cyrillicStr.length; i++) {
latinStr = latinStr + this.latinizeSymbol(cyrillicStr, i);
}
return latinStr;
}
latinizeSymbol(cyrillicStr, symbolNum) {
let symbol = cyrillicStr[symbolNum];
let symbolType = this.getSymbolType(symbol);
if (!this.cyrillicPattern.test(symbol)) {
return symbol;
}
else if (symbolType === 'upper') {
let alphabetIndex = cyrillicAlphabet.indexOf(symbol.toLowerCase());
return this.capitalizeFirstLetter(latinVersion[alphabetIndex]);
}
else if (symbolType === 'lower') {
return latinVersion[cyrillicAlphabet.indexOf(symbol)];
} else {
console.log('unknown symbol detected: ' + symbol);
}
}
getSymbolType(symbol) {
if (symbol == symbol.toUpperCase()) {
return 'upper';
}
if (symbol == symbol.toLowerCase()) {
return 'lower';
}
}
getTextNodes() {
var n,
a = [],
walk = document.createTreeWalker( document.body,NodeFilter.SHOW_TEXT,null,false);
while ( n = walk.nextNode()) {
a.push(n);
}
return a;
}
capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
window.addEventListener('load', function() {
const latinizator = new Lacinka();
});