Skip to content

Commit

Permalink
[Fix] quoteStyle: properly escape only the containing quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Nov 8, 2024
1 parent 450680c commit 5137f8f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ var quotes = {
'double': '"',
single: "'"
};
var quoteREs = {
__proto__: null,
'double': /(["\\])/g,
single: /(['\\])/g
};

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

Expand Down
4 changes: 2 additions & 2 deletions test/quoteStyle.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ test('quoteStyle option', function (t) {
t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value');

t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"');
t.equal(inspect('"', { quoteStyle: 'double' }), '"""', 'double quote, quoteStyle: "double"');
t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"');

t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"');
t.equal(inspect('\'', { quoteStyle: 'double' }), '"\\\'"', 'single quote, quoteStyle: "double"');
t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"');

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

0 comments on commit 5137f8f

Please sign in to comment.