format.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { ENUM_PINYIN_STYLE, PHONETIC_SYMBOL, INITIALS } from "./constant";
  2. import { hasKey } from "./util";
  3. function initials(py) {
  4. for (let i = 0, l = INITIALS.length; i < l; i++) {
  5. if (py.indexOf(INITIALS[i]) === 0) {
  6. return INITIALS[i];
  7. }
  8. }
  9. return "";
  10. }
  11. const RE_PHONETIC_SYMBOL = new RegExp("([" + Object.keys(PHONETIC_SYMBOL).join("") + "])", "g");
  12. const RE_TONE2 = /([aeoiuvnm])([0-4])$/;
  13. export function toFixed(pinyin, style) {
  14. let tone = "";
  15. let first_letter;
  16. let py;
  17. switch (style) {
  18. case ENUM_PINYIN_STYLE.INITIALS:
  19. return initials(pinyin);
  20. case ENUM_PINYIN_STYLE.FIRST_LETTER:
  21. first_letter = pinyin.charAt(0);
  22. if (hasKey(PHONETIC_SYMBOL, first_letter)) {
  23. first_letter = PHONETIC_SYMBOL[first_letter].charAt(0);
  24. }
  25. return first_letter;
  26. case ENUM_PINYIN_STYLE.NORMAL:
  27. return pinyin.replace(RE_PHONETIC_SYMBOL, function ($0, $1_phonetic) {
  28. return PHONETIC_SYMBOL[$1_phonetic].replace(RE_TONE2, "$1");
  29. });
  30. case ENUM_PINYIN_STYLE.PASSPORT:
  31. return pinyin.replace(RE_PHONETIC_SYMBOL, function ($0, $1_phonetic) {
  32. return PHONETIC_SYMBOL[$1_phonetic].replace(RE_TONE2, "$1").replace("v", "YU");
  33. }).toUpperCase();
  34. case ENUM_PINYIN_STYLE.TO3NE:
  35. return pinyin.replace(RE_PHONETIC_SYMBOL, function ($0, $1_phonetic) {
  36. return PHONETIC_SYMBOL[$1_phonetic];
  37. });
  38. case ENUM_PINYIN_STYLE.TONE2:
  39. py = pinyin.replace(RE_PHONETIC_SYMBOL, function ($0, $1) {
  40. tone = PHONETIC_SYMBOL[$1].replace(RE_TONE2, "$2");
  41. return PHONETIC_SYMBOL[$1].replace(RE_TONE2, "$1");
  42. });
  43. return py + tone;
  44. case ENUM_PINYIN_STYLE.TONE:
  45. default:
  46. return pinyin;
  47. }
  48. }
  49. //# sourceMappingURL=format.js.map