Skip to content

Commit

Permalink
util: stringToUnicodeEntities func
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
  • Loading branch information
crazy-max committed Jun 18, 2024
1 parent 3162c09 commit e26a82d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
27 changes: 27 additions & 0 deletions __tests__/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,33 @@ describe('generateRandomString', () => {
});
});

describe('stringToUnicodeEntities', () => {
it('should convert a string to Unicode entities', () => {
const input = 'Hello, World!';
const expected = '&#x48;&#x65;&#x6c;&#x6c;&#x6f;&#x2c;&#x20;&#x57;&#x6f;&#x72;&#x6c;&#x64;&#x21;';
const result = Util.stringToUnicodeEntities(input);
expect(result).toEqual(expected);
});
it('should handle an empty string', () => {
const input = '';
const expected = '';
const result = Util.stringToUnicodeEntities(input);
expect(result).toEqual(expected);
});
it('should handle special characters', () => {
const input = '@#^&*()';
const expected = '&#x40;&#x23;&#x5e;&#x26;&#x2a;&#x28;&#x29;';
const result = Util.stringToUnicodeEntities(input);
expect(result).toEqual(expected);
});
it('should handle non-English characters', () => {
const input = 'こんにちは';
const expected = '&#x3053;&#x3093;&#x306b;&#x3061;&#x306f;';
const result = Util.stringToUnicodeEntities(input);
expect(result).toEqual(expected);
});
});

// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
function getInputName(name: string): string {
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;
Expand Down
6 changes: 6 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,10 @@ export class Util {
const bytes = crypto.randomBytes(Math.ceil(length / 2));
return bytes.toString('hex').slice(0, length);
}

public static stringToUnicodeEntities(str: string) {
return Array.from(str)
.map(char => `&#x${char.charCodeAt(0).toString(16)};`)
.join('');
}
}

0 comments on commit e26a82d

Please sign in to comment.