Skip to content

Commit

Permalink
Properly escape strings before converting to RegExp pattern.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmacarthur committed Mar 24, 2022
1 parent daa3f12 commit 37a7818
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "striff",
"description": "Real simple string diffing.",
"author": "Alex MacArthur (https://macarthur.me)",
"version": "1.0.1",
"version": "1.0.2",
"main": "dist/index.umd.js",
"module": "dist/index.es.js",
"types": "dist/index.d.ts",
Expand Down
7 changes: 7 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ it("Correctly diffs when strings are identical.", () => {
expect(removed).toHaveLength(0);
});

it("Strings are RegEx-escaped", () => {
const { added, removed } = striff("Hi?", "Hi!");

expect(removed).toEqual([{ value: "?", index: 2 }]);
expect(added).toEqual([{ value: "!", index: 2 }]);
});

describe("characters are added", () => {
it("Correctly diffs when characters are added to end.", () => {
const { added, removed } = striff("abc", "abcd");
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ const getDiff = (partsArr: Character[][], arr1: Character[], arr2: Character[])

partsArr.forEach((part: Character[]) => {
let partString = fromCharacters(part);
let pattern = new RegExp(partString);

// One day, `RegExp.replace` will hopefully be built-in.
let pattern = new RegExp(partString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));

// If this little thing matches ANY part of the string, it's in.
let result = pattern.exec(str2);
Expand Down

0 comments on commit 37a7818

Please sign in to comment.