Chore: Correctly escape strings in JSONFormatter (#44096)

* Chore: Properly escape double-quotes in strings in JSONFormatter

* escape slashes
This commit is contained in:
Josh Hunt 2022-01-21 14:51:59 +00:00 committed by GitHub
parent 8ee3f59cd4
commit bddf3d7558
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 3 deletions

View File

@ -0,0 +1,45 @@
import { formatString } from './helpers';
describe('JSONFormatter helpers', () => {
describe('escapeString', () => {
it("does not escape strings that don't contain quotes", () => {
const input = 'hello world';
const expected = 'hello world';
const result = formatString(input);
expect(result).toEqual(expected);
});
it('does not escape strings that contain single quotes', () => {
const input = `'hello world'`;
const expected = `'hello world'`;
const result = formatString(input);
expect(result).toEqual(expected);
});
it('does escapes strings that contain one double quote', () => {
const input = `"hello world`;
const expected = `\\"hello world`;
const result = formatString(input);
expect(result).toEqual(expected);
});
it('does escapes strings that contain two double quotes', () => {
const input = `"hello world"`;
const expected = `\\"hello world\\"`;
const result = formatString(input);
expect(result).toEqual(expected);
});
it('does escapes a string that looks like JSON', () => {
const input = `{"hello": "world"}`;
const expected = `{\\"hello\\": \\"world\\"}`;
const result = formatString(input);
expect(result).toEqual(expected);
});
});
});

View File

@ -4,8 +4,8 @@
/*
* Escapes `"` characters from string
*/
function escapeString(str: string): string {
return str.replace('"', '"');
export function formatString(str: string): string {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
/*
@ -62,7 +62,7 @@ export function getValuePreview(object: object, value: string): string {
}
if (type === 'string') {
value = '"' + escapeString(value) + '"';
value = '"' + formatString(value) + '"';
}
if (type === 'function') {
// Remove content of the function