From 5137f8f7bea69a7fc671bb683fd35f244f38fc52 Mon Sep 17 00:00:00 2001 From: Jordan Harband Date: Fri, 8 Nov 2024 15:06:40 +0000 Subject: [PATCH] [Fix] `quoteStyle`: properly escape only the containing quotes --- index.js | 9 ++++++++- test/quoteStyle.js | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 6c2f944..5240a4d 100644 --- a/index.js +++ b/index.js @@ -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 || {}; @@ -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); } diff --git a/test/quoteStyle.js b/test/quoteStyle.js index 66569b0..da23e63 100644 --- a/test/quoteStyle.js +++ b/test/quoteStyle.js @@ -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"');