diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.test.ts index a4a1d977a207f..906319865c21f 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.test.ts @@ -14,6 +14,13 @@ describe('Kuery escape', () => { expect(escapeQuotes(value)).toBe(expected); }); + test('should escape backslashes and quotes', () => { + const value = 'Backslashes \\" in the middle and ends with quotes \\"'; + const expected = 'Backslashes \\\\\\" in the middle and ends with quotes \\\\\\"'; + + expect(escapeQuotes(value)).toBe(expected); + }); + test('should escape special characters', () => { const value = `This \\ has (a lot of) characters, don't you *think*? "Yes."`; const expected = `This \\\\ has \\(a lot of\\) \\ characters, don't you \\*think\\*? \\"Yes.\\"`; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts index 2ddb3966bb560..6ccf8f577fbec 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts @@ -6,8 +6,12 @@ import { flow } from 'lodash'; +/** + * Escapes backslashes and double-quotes. (Useful when putting a string in quotes to use as a value + * in a KQL expression. See the QuotedCharacter rule in kuery.peg.) + */ export function escapeQuotes(str: string) { - return str.replace(/"/g, '\\"'); + return str.replace(/[\\"]/g, '\\$&'); } export const escapeKuery = flow(escapeSpecialCharacters, escapeAndOr, escapeNot, escapeWhitespace);