diff --git a/web/src/services/Assertion.service.ts b/web/src/services/Assertion.service.ts index acec18d9a8..2c9f39e132 100644 --- a/web/src/services/Assertion.service.ts +++ b/web/src/services/Assertion.service.ts @@ -18,7 +18,7 @@ const AssertionService = () => ({ if (!input) return input; const formatted = input.trim(); - if (isJson(input)) return `'${input}'`; + if (isJson(input)) return `'${this.escapeString(input, `'`)}'`; if (Object.values(Attributes).includes(formatted)) return formatted; if (Object.values(Attributes).some(aa => formatted.includes(aa))) return formatted; @@ -29,7 +29,28 @@ const AssertionService = () => ({ return isQuoted ? formatted : this.quotedString(formatted); }, quotedString(str: string): string { - return `\"${str}\"`; + return `\"${this.escapeString(str, `"`)}\"`; + }, + escapeString(str: string, quoteCharacter: string): string { + // Couldn't find a regex to solve this problem :( + // Feel free to refactor this if you know how to escape quotes without + // double escaping already escaped quotes. + // + // Examples: + // ' ==> \\' + // \\' ==> \\' + let newString = ''; + let lastCharacter = ''; + for (let i = 0; i < str.length; i++) { + if (str[i] == quoteCharacter && lastCharacter != '\\') { + newString += `\\${quoteCharacter}`; + } else { + newString += str[i]; + } + + lastCharacter = str[i]; + } + return newString; }, getSpanIds(resultList: TRawAssertionResult[]) { const spanIds = resultList diff --git a/web/src/services/__tests__/Assertion.service.test.ts b/web/src/services/__tests__/Assertion.service.test.ts index 8b3da14038..c122a1cf10 100644 --- a/web/src/services/__tests__/Assertion.service.test.ts +++ b/web/src/services/__tests__/Assertion.service.test.ts @@ -39,4 +39,17 @@ describe('AssertionService', () => { expect(result).toEqual([id1, id2, id3]); }); }); + describe('escapeString', () => { + it('should escape simple quotes', () => { + const {escapeString} = AssertionService + const escaped = escapeString(`'This should be escaped'`, `'`); + expect(escaped).toBe(`\\'This should be escaped\\'`); + }) + + it('should not escape already escaped string', () => { + const {escapeString} = AssertionService + const escaped = escapeString(`\\'This should be escaped\\'`, `'`); + expect(escaped).toBe(`\\'This should be escaped\\'`); + }) + }); });