فهرست منبع

fixed string to unicode conversion

sanex3339 9 سال پیش
والد
کامیت
f66b937ea5
2فایلهای تغییر یافته به همراه16 افزوده شده و 10 حذف شده
  1. 6 4
      dist/src/Utils.js
  2. 10 6
      src/Utils.ts

+ 6 - 4
dist/src/Utils.js

@@ -41,13 +41,15 @@ class Utils {
         return obj;
     }
     static stringToUnicode(string) {
-        const radix = 16, unicodeSliceValue = -4;
-        let regexp = new RegExp('[\x00-\x7F]');
+        const radix = 16;
+        let regexp = new RegExp('[\x00-\x7F]'), template;
         return `'${string.replace(/[\s\S]/g, (escape) => {
             if (regexp.test(escape)) {
-                return '\\x' + escape.charCodeAt(0).toString(radix);
+                template = '0'.repeat(2);
+                return `\\x${(template + escape.charCodeAt(0).toString(radix)).slice(-template.length)}`;
             }
-            return `\\u${('0000' + escape.charCodeAt(0).toString(radix)).slice(unicodeSliceValue)}`;
+            template = '0'.repeat(4);
+            return `\\u${(template + escape.charCodeAt(0).toString(radix)).slice(-template.length)}`;
         })}'`;
     }
 }

+ 10 - 6
src/Utils.ts

@@ -97,17 +97,21 @@ export class Utils {
      * @returns {string}
      */
     public static stringToUnicode (string: string): string {
-        const radix: number = 16,
-            unicodeSliceValue: number = -4;
+        const radix: number = 16;
 
-        let regexp: RegExp = new RegExp('[\x00-\x7F]');
+        let regexp: RegExp = new RegExp('[\x00-\x7F]'),
+            template: string;
 
         return `'${string.replace(/[\s\S]/g, (escape: string): string => {
             if (regexp.test(escape)) {
-                return '\\x' + escape.charCodeAt(0).toString(radix);
+                template = '0'.repeat(2);
+                
+                return `\\x${(template + escape.charCodeAt(0).toString(radix)).slice(-template.length)}`;
             }
-
-            return `\\u${('0000' + escape.charCodeAt(0).toString(radix)).slice(unicodeSliceValue)}`;
+            
+            template = '0'.repeat(4);
+            
+            return `\\u${(template + escape.charCodeAt(0).toString(radix)).slice(-template.length)}`;
         })}'`;
     }
 }