Skip to content

Commit 5137f8f

Browse files
committed
[Fix] quoteStyle: properly escape only the containing quotes
1 parent 450680c commit 5137f8f

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

index.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ var quotes = {
7474
'double': '"',
7575
single: "'"
7676
};
77+
var quoteREs = {
78+
__proto__: null,
79+
'double': /(["\\])/g,
80+
single: /(['\\])/g
81+
};
7782

7883
module.exports = function inspect_(obj, options, depth, seen) {
7984
var opts = options || {};
@@ -432,8 +437,10 @@ function inspectString(str, opts) {
432437
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
433438
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
434439
}
440+
var quoteRE = quoteREs[opts.quoteStyle || 'single'];
441+
quoteRE.lastIndex = 0;
435442
// eslint-disable-next-line no-control-regex
436-
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
443+
var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte);
437444
return wrapQuotes(s, 'single', opts);
438445
}
439446

test/quoteStyle.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ test('quoteStyle option', function (t) {
1414
t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value');
1515

1616
t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"');
17-
t.equal(inspect('"', { quoteStyle: 'double' }), '"""', 'double quote, quoteStyle: "double"');
17+
t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"');
1818

1919
t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"');
20-
t.equal(inspect('\'', { quoteStyle: 'double' }), '"\\\'"', 'single quote, quoteStyle: "double"');
20+
t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"');
2121

2222
t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"');
2323
t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"');

0 commit comments

Comments
 (0)