index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. var GROUP_LEFT_TO_RIGHT,
  3. GROUP_RIGHT_TO_LEFT,
  4. EXPRESSION_LEFT_TO_RIGHT,
  5. EXPRESSION_RIGHT_TO_LEFT;
  6. /*
  7. * Character ranges of left-to-right characters.
  8. */
  9. GROUP_LEFT_TO_RIGHT = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6' +
  10. '\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C' +
  11. '\uFE00-\uFE6F\uFEFD-\uFFFF';
  12. /*
  13. * Character ranges of right-to-left characters.
  14. */
  15. GROUP_RIGHT_TO_LEFT = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC';
  16. /*
  17. * Expression to match a left-to-right string.
  18. *
  19. * Matches the start of a string, followed by zero or
  20. * more non-right-to-left characters, followed by a
  21. * left-to-right character.
  22. */
  23. EXPRESSION_LEFT_TO_RIGHT = new RegExp(
  24. '^[^' + GROUP_RIGHT_TO_LEFT + ']*[' + GROUP_LEFT_TO_RIGHT + ']'
  25. );
  26. /*
  27. * Expression to match a right-to-left string.
  28. *
  29. * Matches the start of a string, followed by zero or
  30. * more non-left-to-right characters, followed by a
  31. * right-to-left character.
  32. */
  33. EXPRESSION_RIGHT_TO_LEFT = new RegExp(
  34. '^[^' + GROUP_LEFT_TO_RIGHT + ']*[' + GROUP_RIGHT_TO_LEFT + ']'
  35. );
  36. /**
  37. * Detect the direction of text.
  38. *
  39. * @param {string} value - value to stringify and check.
  40. * @return {string} - One of `"rtl"`, `"ltr"`, or
  41. * `"neutral"`.
  42. */
  43. function direction(value) {
  44. value = value.toString();
  45. if (EXPRESSION_RIGHT_TO_LEFT.test(value)) {
  46. return 'rtl';
  47. }
  48. if (EXPRESSION_LEFT_TO_RIGHT.test(value)) {
  49. return 'ltr';
  50. }
  51. return 'neutral';
  52. }
  53. /*
  54. * Expose `direction`.
  55. */
  56. module.exports = direction;