Skip to content

Commit 77be3c8

Browse files
committed
Fix stripping non-breaking comments in code when preserving whitespace
Fixes #64
1 parent 8892dd2 commit 77be3c8

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ const singleComment = Symbol('singleComment');
22
const multiComment = Symbol('multiComment');
33

44
const stripWithoutWhitespace = () => '';
5-
const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
5+
6+
// Replace all characters except ASCII spaces, tabs and line endings with regular spaces to ensure valid JSON output.
7+
const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/[^ \t\r\n]/g, ' ');
68

79
const isEscaped = (jsonString, quotePosition) => {
810
let index = quotePosition - 1;

test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,13 @@ test.failing('handles malformed block comments', t => {
7878
t.is(stripJsonComments('[] */'), '[] */');
7979
t.is(stripJsonComments('[] /*'), '[] /*'); // Fails
8080
});
81+
82+
test('handles non-breaking space with preserving whitespace', t => {
83+
const fixture = `{
84+
// Comment with non-breaking-space: '\u00A0'
85+
"a": 1
86+
}`;
87+
88+
const stripped = stripJsonComments(fixture);
89+
t.deepEqual(JSON.parse(stripped), {a: 1});
90+
});

0 commit comments

Comments
 (0)