8
0

unicode.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * Set of utils to handle unicode characters.
  7. *
  8. * @module utils/unicode
  9. */
  10. /**
  11. * Checks whether given `character` is a combining mark.
  12. *
  13. * @param {String} character Character to check.
  14. * @returns {Boolean}
  15. */
  16. export function isCombiningMark( character ) {
  17. // eslint-disable-next-line no-misleading-character-class
  18. return !!character && character.length == 1 && /[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]/.test( character );
  19. }
  20. /**
  21. * Checks whether given `character` is a high half of surrogate pair.
  22. *
  23. * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair
  24. * consist of high surrogate pair character followed by low surrogate pair character.
  25. *
  26. * @param {String} character Character to check.
  27. * @returns {Boolean}
  28. */
  29. export function isHighSurrogateHalf( character ) {
  30. return !!character && character.length == 1 && /[\ud800-\udbff]/.test( character );
  31. }
  32. /**
  33. * Checks whether given `character` is a low half of surrogate pair.
  34. *
  35. * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair
  36. * consist of high surrogate pair character followed by low surrogate pair character.
  37. *
  38. * @param {String} character Character to check.
  39. * @returns {Boolean}
  40. */
  41. export function isLowSurrogateHalf( character ) {
  42. return !!character && character.length == 1 && /[\udc00-\udfff]/.test( character );
  43. }
  44. /**
  45. * Checks whether given offset in a string is inside a surrogate pair (between two surrogate halves).
  46. *
  47. * @param {String} string String to check.
  48. * @param {Number} offset Offset to check.
  49. * @returns {Boolean}
  50. */
  51. export function isInsideSurrogatePair( string, offset ) {
  52. return isHighSurrogateHalf( string.charAt( offset - 1 ) ) && isLowSurrogateHalf( string.charAt( offset ) );
  53. }
  54. /**
  55. * Checks whether given offset in a string is between base character and combining mark or between two combining marks.
  56. *
  57. * @param {String} string String to check.
  58. * @param {Number} offset Offset to check.
  59. * @returns {Boolean}
  60. */
  61. export function isInsideCombinedSymbol( string, offset ) {
  62. return isCombiningMark( string.charAt( offset ) );
  63. }