diff --git a/src/utils/predicateBuilder/stringSplitter.ts b/src/utils/predicateBuilder/stringSplitter.ts index 5e792237..56c84af5 100644 --- a/src/utils/predicateBuilder/stringSplitter.ts +++ b/src/utils/predicateBuilder/stringSplitter.ts @@ -1,6 +1,6 @@ import splitter = require('split-string'); -const regexMatcher = /^\/(.+)\/([igmsuy]*)$/i; +const regexMatcher = /^\/(.+)\/(i)?$/i; const regexParser = (input: string): string | RegExp => { const match = regexMatcher.exec(input); @@ -10,13 +10,21 @@ const regexParser = (input: string): string | RegExp => { return new RegExp(match[1], match[2]); }; -const quotes = [`/`]; +const quotes = [`"`, `'`, `\``]; +const splitterDefaults = { + quotes, + brackets: { + ' /': `/`, + ',/': `/`, + '/': `/`, + }, +}; const spaceSplitter = (str: string): string[] => { // @ts-ignore return splitter(str, { separator: ` `, - quotes, + ...splitterDefaults, }); }; @@ -24,15 +32,28 @@ const commaSplitter = (str: string): string[] => { // @ts-ignore return splitter(str, { separator: `,`, - quotes, + ...splitterDefaults, }); }; -const trimmer = (str: string): string => str.trim(); +const quouteStip = () => { + let stripped = false; + return (str: string, quote: string): string => { + if (!stripped && str.startsWith(quote) && str.endsWith(quote)) { + stripped = true; + return str.substr(1, str.length - 2); + } + return str; + }; +}; + +const trimmer = (str: string): string => { + return quotes.reduce(quouteStip(), str); +}; export const split = (str: string | undefined): (string | RegExp)[] => { if (!str) { return []; } - return commaSplitter(str).flatMap(spaceSplitter).map(trimmer).filter(Boolean).map(regexParser); + return commaSplitter(` ${str}`).flatMap(spaceSplitter).map(trimmer).filter(Boolean).map(regexParser); }; diff --git a/test/src/utils/predicateBuilder/stringSplitter.spec.ts b/test/src/utils/predicateBuilder/stringSplitter.spec.ts index f2051f88..212faf94 100644 --- a/test/src/utils/predicateBuilder/stringSplitter.spec.ts +++ b/test/src/utils/predicateBuilder/stringSplitter.spec.ts @@ -14,7 +14,7 @@ describe(`string splitter`, () => { }); it(`should split by space`, () => { - expect(split(`a b c d`)).toEqual([`a`, `b`, `c`, `d`]); + expect(split(`a "b " c d 'f g' \`',f\``)).toEqual([`a`, `b `, `c`, `d`, `f g`, `',f`]); }); it(`should split by comma`, () => { @@ -29,6 +29,10 @@ describe(`string splitter`, () => { expect(split(`a/sdf/f`)).toEqual([`a/sdf/f`]); }); + it(`should parse regex with / in it`, () => { + expect(split(`/sd\\/f/`)).toEqual([/sd\/f/]); + }); + it(`should not confuse regex with wrong flags`, () => { expect(split(`/s/pm`)).toEqual([`/s/pm`]); }); @@ -45,7 +49,4 @@ describe(`string splitter`, () => { expect(split(`/a/i`)).toEqual([/a/i]); }); - it(`should handle based on regex global flag`, () => { - expect(split(`/a/g`)).toEqual([/a/g]); - }); });