|
1 | 1 |
|
2 | | -var isAlpha = function(char) { |
3 | | - return /^[A-Za-z]$/.test(char); |
| 2 | +String.prototype.isAlpha = function() { |
| 3 | + |
| 4 | + return /^[A-Za-z]$/.test(this); |
| 5 | +} |
| 6 | + |
| 7 | +String.prototype.isPinyinVowel = function() { |
| 8 | + |
| 9 | + return /^[aeiouv\u00fc]$/.test(this); |
| 10 | +} |
| 11 | + |
| 12 | +/** |
| 13 | + * Unicode tone marks (in order) |
| 14 | + * a: u0101 u00e1 u01ce u00e0 |
| 15 | + * e: u0113 u00e9 u011b u00e8 |
| 16 | + * i: u012b u00ed u01d0 u00ec |
| 17 | + * o: u014d u00f3 u01d2 u00f2 |
| 18 | + * u: u016b u00fa u01d4 u00f9 |
| 19 | + * v: u01d6 u01d8 u01da u01dc |
| 20 | + */ |
| 21 | +String.prototype.convertPinyin = function() { |
| 22 | + |
| 23 | + //TODO |
4 | 24 | } |
5 | 25 |
|
6 | 26 | var pinyinify = function(str) { |
7 | 27 |
|
| 28 | + if (typeof str !== 'string') { |
| 29 | + |
| 30 | + return str; |
| 31 | + } |
| 32 | + |
8 | 33 | var res = ""; |
9 | | - for (var i = 0; i < str.length; i++) { |
| 34 | + var i = 0; |
| 35 | + while (str.length > 0) { |
| 36 | + |
10 | 37 | var char = str.charAt(i); |
11 | | - if (isAlpha(char)) { |
12 | | - //TODO look for index of tone number |
| 38 | + if (char.isAlpha()) { |
| 39 | + |
| 40 | + res += str.substring(0, i); |
| 41 | + str = str.substring(i); |
| 42 | + i = 0; |
| 43 | + var toneNumIndex = str.search(/[1-5]/); |
| 44 | + if (toneNumIndex > 0 && toneNumIndex < 7) { |
| 45 | + res += str.substring(0, toneNumIndex + 1).convertPinyin(); |
| 46 | + str = str.substring(toneNumIndex + 1); |
| 47 | + |
| 48 | + } else { |
| 49 | + |
| 50 | + var whitespaceIndex = str.search(/\s/); |
| 51 | + if (whitespaceIndex < 0) { |
| 52 | + |
| 53 | + res += str.substring(0); |
| 54 | + str = ""; |
| 55 | + } else { |
| 56 | + |
| 57 | + res += str.substring(0, whitespaceIndex + 1); |
| 58 | + str = str.substring(whitespaceIndex + 1); |
| 59 | + } |
| 60 | + } |
| 61 | + |
13 | 62 | } else { |
14 | | - res += char; |
| 63 | + |
| 64 | + i++; |
15 | 65 | } |
16 | 66 | } |
17 | 67 |
|
|
0 commit comments