From 6fe20ce103dd9647dfc7712a44987c6e70ab2b2c Mon Sep 17 00:00:00 2001 From: Andrii Dieiev Date: Mon, 12 Dec 2016 22:46:04 +0200 Subject: [PATCH] Fix escapeRegExp and add test --- src/utils.ts | 2 +- test/utilsTests.ts | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 71ced1e92b0..8820f3cdd43 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -97,5 +97,5 @@ export function stripComments(content: string): string { * Escapes all special characters in RegExp pattern to avoid broken regular expressions and ensure proper matches */ export function escapeRegExp(re: string): string { - return re.replace(/[.+*?|^$\[]{}()\\]/g, "$&"); + return re.replace(/[.+*?|^$[\]{}()\\]/g, "\\$&"); } diff --git a/test/utilsTests.ts b/test/utilsTests.ts index 52206e3d151..37cfbcee5e3 100644 --- a/test/utilsTests.ts +++ b/test/utilsTests.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {arrayify, dedent, objectify} from "../src/utils"; +import {arrayify, dedent, escapeRegExp, objectify} from "../src/utils"; describe("Utils", () => { it("arrayify", () => { @@ -46,4 +46,15 @@ describe("Utils", () => { assert.equal(dedent` `, " "); assert.equal(dedent``, ""); }); + + it("escapeRegExp", () => { + const plus = escapeRegExp("(a+|d)?b[ci]{2,}"); + const plusRe = new RegExp(plus); + + // contains substring that matches regular expression pattern + assert.equal(plusRe.test("regexpaaaabcicmatch"), false); + + // properly matches exact string with special characters + assert.equal(plusRe.test("string(a+|d)?b[ci]{2,}match"), true); + }); });