diff --git a/src/components/search_bar/query/default_syntax.test.ts b/src/components/search_bar/query/default_syntax.test.ts index 0064a45938d..d240b4bfb1e 100644 --- a/src/components/search_bar/query/default_syntax.test.ts +++ b/src/components/search_bar/query/default_syntax.test.ts @@ -639,6 +639,33 @@ describe('defaultSyntax', () => { expect(printedQuery).toBe(query); }); + describe('phrases with special characters', () => { + const wrappedSpecialChars = "~`!@#$%^&+={}[];',.?".split(''); + + wrappedSpecialChars.forEach((char) => { + test(`${char} should be wrapped in quotes`, () => { + const query = `user:("foo${char}bar")`; + + const ast = defaultSyntax.parse(query); + const printedQuery = defaultSyntax.print(ast); + expect(printedQuery).toBe(query); + }); + }); + + const unwrappedSpecialChars = ['\\"', '(', ')', '_', '-', ':', '*', '\\']; + + unwrappedSpecialChars.forEach((char) => { + test(`${char} should not be wrapped in quotes`, () => { + const query = `user:("foo${char}bar")`; + const expected = `user:(foo${char.replaceAll('\\', '')}bar)`; + + const ast = defaultSyntax.parse(query); + const printedQuery = defaultSyntax.print(ast); + expect(printedQuery).toBe(expected); + }); + }); + }); + test('single term or expression', () => { const query = 'f:(foo)'; const ast = defaultSyntax.parse(query); diff --git a/src/components/search_bar/query/default_syntax.ts b/src/components/search_bar/query/default_syntax.ts index f5579819fc0..4679a53e222 100644 --- a/src/components/search_bar/query/default_syntax.ts +++ b/src/components/search_bar/query/default_syntax.ts @@ -451,7 +451,11 @@ const printValue = (value: Value, options: ParseOptions) => { return value.toString(); } - if (value.length === 0 || value.match(/\s/) || value.toLowerCase() === 'or') { + if ( + value.length === 0 || + value.match(/[^\w\-_*:()"/\\]/) || // Escape spaces and special characters not used as syntax identifiers + value.toLowerCase() === 'or' + ) { return `"${escapePhraseValue(value)}"`; } diff --git a/upcoming_changelogs/6356.md b/upcoming_changelogs/6356.md new file mode 100644 index 00000000000..2c5911e544b --- /dev/null +++ b/upcoming_changelogs/6356.md @@ -0,0 +1 @@ +- `EuiSearchBar` now automatically wraps special characters not used by query syntax in quotes