unicode.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. return !!character && character.length == 1 && /[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]/.test( character );
  18. }
  19. /**
  20. * Checks whether given `character` is a high half of surrogate pair.
  21. *
  22. * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair
  23. * consist of high surrogate pair character followed by low surrogate pair character.
  24. *
  25. * @param {String} character Character to check.
  26. * @returns {Boolean}
  27. */
  28. export function isHighSurrogateHalf( character ) {
  29. return !!character && character.length == 1 && /[\ud800-\udbff]/.test( character );
  30. }
  31. /**
  32. * Checks whether given `character` is a low half of surrogate pair.
  33. *
  34. * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair
  35. * consist of high surrogate pair character followed by low surrogate pair character.
  36. *
  37. * @param {String} character Character to check.
  38. * @returns {Boolean}
  39. */
  40. export function isLowSurrogateHalf( character ) {
  41. return !!character && character.length == 1 && /[\udc00-\udfff]/.test( character );
  42. }
  43. /**
  44. * Checks whether given offset in a string is inside a surrogate pair (between two surrogate halves).
  45. *
  46. * @param {String} string String to check.
  47. * @param {Number} offset Offset to check.
  48. * @returns {Boolean}
  49. */
  50. export function isInsideSurrogatePair( string, offset ) {
  51. return isHighSurrogateHalf( string.charAt( offset - 1 ) ) && isLowSurrogateHalf( string.charAt( offset ) );
  52. }
  53. /**
  54. * Checks whether given offset in a string is between base character and combining mark or between two combining marks.
  55. *
  56. * @param {String} string String to check.
  57. * @param {Number} offset Offset to check.
  58. * @returns {Boolean}
  59. */
  60. export function isInsideCombinedSymbol( string, offset ) {
  61. return isCombiningMark( string.charAt( offset ) );
  62. }