MCPcopy Create free account
hub / github.com/Kong/httpsnippet / escapeString

Function escapeString

src/helpers/escape.ts:33–70  ·  view source on GitHub ↗
(rawValue: any, options: EscapeOptions = {})

Source from the content-addressed store, hash-verified

31 * for the complete original algorithm.
32 */
33export function escapeString(rawValue: any, options: EscapeOptions = {}) {
34 const { delimiter = '"', escapeChar = '\\', escapeNewlines = true } = options;
35
36 const stringValue = rawValue.toString();
37
38 return [...stringValue]
39 .map(c => {
40 if (c === '\b') {
41 return `${escapeChar}b`;
42 } else if (c === '\t') {
43 return `${escapeChar}t`;
44 } else if (c === '\n') {
45 if (escapeNewlines) {
46 return `${escapeChar}n`;
47 }
48 return c; // Don't just continue, or this is caught by < \u0020
49 } else if (c === '\f') {
50 return `${escapeChar}f`;
51 } else if (c === '\r') {
52 if (escapeNewlines) {
53 return `${escapeChar}r`;
54 }
55 return c; // Don't just continue, or this is caught by < \u0020
56 } else if (c === escapeChar) {
57 return escapeChar + escapeChar;
58 } else if (c === delimiter) {
59 return escapeChar + delimiter;
60 } else if (c < '\u0020' || c > '\u007E') {
61 // Delegate the trickier non-ASCII cases to the normal algorithm. Some of these
62 // are escaped as \uXXXX, whilst others are represented literally. Since we're
63 // using this primarily for header values that are generally (though not 100%
64 // strictly?) ASCII-only, this should almost never happen.
65 return JSON.stringify(c).slice(1, -1);
66 }
67 return c;
68 })
69 .join('');
70}
71
72/**
73 * Make a string value safe to insert literally into a snippet within single quotes,

Callers 5

escape.test.tsFile · 0.90
convertTypeFunction · 0.90
convertFunction · 0.90
escapeForSingleQuotesFunction · 0.85
escapeForDoubleQuotesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…