stringTools.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Helper to manipulate strings
  3. */
  4. export class StringTools {
  5. /**
  6. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  7. * @param str Source string
  8. * @param suffix Suffix to search for in the source string
  9. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  10. */
  11. public static EndsWith(str: string, suffix: string): boolean {
  12. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  13. }
  14. /**
  15. * Checks for a matching suffix at the beginning of a string (for ES5 and lower)
  16. * @param str Source string
  17. * @param suffix Suffix to search for in the source string
  18. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  19. */
  20. public static StartsWith(str: string, suffix: string): boolean {
  21. return str.indexOf(suffix) === 0;
  22. }
  23. /**
  24. * Decodes a buffer into a string
  25. * @param buffer The buffer to decode
  26. * @returns The decoded string
  27. */
  28. public static Decode(buffer: Uint8Array | Uint16Array): string {
  29. if (typeof TextDecoder !== "undefined") {
  30. return new TextDecoder().decode(buffer);
  31. }
  32. let result = "";
  33. for (let i = 0; i < buffer.byteLength; i++) {
  34. result += String.fromCharCode(buffer[i]);
  35. }
  36. return result;
  37. }
  38. /**
  39. * Encode a buffer to a base64 string
  40. * @param buffer defines the buffer to encode
  41. * @returns the encoded string
  42. */
  43. public static EncodeArrayBufferToBase64(buffer: ArrayBuffer | ArrayBufferView): string {
  44. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  45. var output = "";
  46. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  47. var i = 0;
  48. var bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer);
  49. while (i < bytes.length) {
  50. chr1 = bytes[i++];
  51. chr2 = i < bytes.length ? bytes[i++] : Number.NaN;
  52. chr3 = i < bytes.length ? bytes[i++] : Number.NaN;
  53. enc1 = chr1 >> 2;
  54. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  55. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  56. enc4 = chr3 & 63;
  57. if (isNaN(chr2)) {
  58. enc3 = enc4 = 64;
  59. } else if (isNaN(chr3)) {
  60. enc4 = 64;
  61. }
  62. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  63. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  64. }
  65. return output;
  66. }
  67. }