Minimize string escapes
If there you are opting in for double quote but there's a string with a double quote in it, it's better to swap to a single quote to avoid having too many `\`. Note that if there are both single and double quotes in the string, we should use the default string instead. Fixes #139master
parent
d25881530f
commit
afca3d7e7a
|
@ -2059,7 +2059,18 @@ function swapQuotes(str) {
|
|||
function nodeStr(str, options) {
|
||||
isString.assert(str);
|
||||
|
||||
if (options.singleQuote) {
|
||||
const containsSingleQuote = str.indexOf("'") !== -1;
|
||||
const containsDoubleQuote = str.indexOf('"') !== -1;
|
||||
|
||||
let shouldUseSingleQuote = options.singleQuote;
|
||||
if (options.singleQuote && containsSingleQuote && !containsDoubleQuote) {
|
||||
shouldUseSingleQuote = false;
|
||||
}
|
||||
if (!options.singleQuote && !containsSingleQuote && containsDoubleQuote) {
|
||||
shouldUseSingleQuote = true;
|
||||
}
|
||||
|
||||
if (shouldUseSingleQuote) {
|
||||
return swapQuotes(JSON.stringify(swapQuotes(str)));
|
||||
} else {
|
||||
return JSON.stringify(str);
|
||||
|
|
|
@ -164,9 +164,7 @@ var ls = child_process.spawn(\"ls\");
|
|||
var wc = child_process.spawn(\"wc\", [ \"-l\" ]);
|
||||
|
||||
// args + options.
|
||||
child_process.spawn(\"echo\", [ \"-n\", \"\\\"Testing...\\\"\" ], {
|
||||
env: { TEST: \"foo\" }
|
||||
});
|
||||
child_process.spawn(\"echo\", [ \"-n\", \'\"Testing...\"\' ], { env: { TEST: \"foo\" } });
|
||||
|
||||
// options only.
|
||||
child_process.spawn(\"echo\", { env: { FOO: 2 } });
|
||||
|
|
|
@ -26,9 +26,9 @@ exports[`test strings.js 1`] = `
|
|||
|
||||
\"\'\";
|
||||
|
||||
\"\\\"\";
|
||||
\"\\\"\";
|
||||
\"\\\\\\\"\";
|
||||
\'\"\';
|
||||
\'\"\';
|
||||
\'\\\\\"\';
|
||||
|
||||
\"\'\";
|
||||
\"\'\";
|
||||
|
|
Loading…
Reference in New Issue