@technobuddha/library
Version:
A large library of useful functions
110 lines (106 loc) • 3.46 kB
text/typescript
import { oct, u4 } from './escape.ts';
import { empty } from './unicode.ts';
// cspell:ignore unnnn
/**
* Escape a string for use in Java
*
* | Character | Hex | Escape Sequence |
* | ------------------ | -------------------- | -------------------- |
* | NUL | 0x00 | \\u0000 |
* | Backspace | 0x08 | \\b |
* | Tab | 0x09 | \\t |
* | Newline | 0x0a | \\n |
* | Form Feed | 0x0c | \\f |
* | Carriage Return | 0x0d | \\r |
* | Double Quote | 0x22 | \\" |
* | Single Quote | 0x27 | \\' |
* | Backslash | 0x5c | \\\\ |
* | Control Characters | 0x00-0x1f, 0x7f-0x9f | \\unnnn |
* | BMP | 0x0100-0xffff | \\unnnn |
* | Astral | 0x10000-0x10ffff | \\unnnn\\unnnn[^1] |
*
* [^1]: Java does not support unicode escapes beyond 0xFFFF. Astral characters must be
* encoded as a two character surrogate pair.
* @param input - The string to escape
* @returns The string escaped for Java
* @example
* ```typescript
* escapeJava('Hello\nWorld'); // "Hello\\nWorld"
* escapeJava('"\\'); // "\\\"\\\\"
* escapeJava('\b'); // "\\b"
* escapeJava('\u20ac'); // "\\u20ac"
* ```
* @group Programming
* @category Escaping
*/
export function escapeJava(input: string): string {
const output: string[] = [];
for (let i = 0; i < input.length; ++i) {
let u0 = input.codePointAt(i)!;
let u1 = input.codePointAt(i + 1);
if (u0 < 0x00000020) {
switch (u0) {
case 0x00000000: {
output.push(oct(u1) ? '\\000' : '\\0');
break;
}
case 0x00000008: {
output.push('\\b');
break;
}
case 0x00000009: {
output.push('\\t');
break;
}
case 0x0000000a: {
output.push('\\n');
break;
}
case 0x0000000c: {
output.push('\\f');
break;
}
case 0x0000000d: {
output.push('\\r');
break;
}
default: {
output.push(u4(u0));
}
}
} else if (u0 < 0x0000007f) {
switch (u0) {
case 0x00000022: {
output.push('\\"');
break;
}
case 0x00000027: {
output.push("\\'");
break;
}
case 0x0000005c: {
output.push('\\\\');
break;
}
default: {
// eslint-disable-next-line unicorn/prefer-code-point
output.push(String.fromCharCode(u0));
}
}
} else if (u0 < 0x000000a1) {
output.push(u4(u0));
} else if (u0 < 0x00000100) {
// eslint-disable-next-line unicorn/prefer-code-point
output.push(String.fromCharCode(u0));
} else if (u0 < 0x00010000) {
output.push(u4(u0));
} else {
// eslint-disable-next-line unicorn/prefer-code-point
u0 = input.charCodeAt(i);
// eslint-disable-next-line unicorn/prefer-code-point
u1 = input.charCodeAt(++i);
output.push(u4(u0), u4(u1));
}
}
return output.join(empty);
}