Skip to content

Commit

Permalink
Correctly handle some weird escaping (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
YuMeiJie authored and sindresorhus committed Apr 30, 2019
1 parent 5f5fdd3 commit 23acbfe
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ const multiComment = Symbol('multiComment');
const stripWithoutWhitespace = () => '';
const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');

const isEscaped = (jsonString, qoutePos) => {
let i = qoutePos - 1;
let numOfBackslash = 0;

while (jsonString[i] === '\\') {
numOfBackslash += 1;
i -= 1;
}

return Boolean(numOfBackslash % 2);
};

module.exports = (jsonString, options = {}) => {
const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;

Expand All @@ -17,7 +29,7 @@ module.exports = (jsonString, options = {}) => {
const nextCharacter = jsonString[i + 1];

if (!insideComment && currentCharacter === '"') {
const escaped = jsonString[i - 1] === '\\' && jsonString[i - 2] !== '\\';
const escaped = isEscaped(jsonString, i);
if (!escaped) {
insideString = !insideString;
}
Expand Down
5 changes: 2 additions & 3 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ test('line endings - works at EOF', t => {
t.is(stripJsonComments('{\r\n\t"a":"b"\r\n} //EOF', options), '{\r\n\t"a":"b"\r\n} ');
});

test.failing('handles weird escaping', t => {
// eslint-disable-next-line no-useless-escape
t.is(stripJsonComments('{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}'), '{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}');
test('handles weird escaping', t => {
t.is(stripJsonComments(String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`), String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`);
});

0 comments on commit 23acbfe

Please sign in to comment.