From e68924499654d7b2fcc04295d0d29d895fa0bbf4 Mon Sep 17 00:00:00 2001 From: evilebottnawi Date: Mon, 19 Feb 2018 17:42:00 +0300 Subject: [PATCH] fix: respec special characters inside string --- src/printer.js | 16 +++++++++++++++- .../literals/__snapshots__/jsfmt.spec.js.snap | 18 ++++++++++++++++++ tests/literals/literals.php | 9 +++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/printer.js b/src/printer.js index 83b280760..0961fe482 100644 --- a/src/printer.js +++ b/src/printer.js @@ -11,6 +11,20 @@ const indent = docBuilders.indent; const hardline = docBuilders.hardline; const softline = docBuilders.softline; +const makeString = util.makeString; + +function stringEscape(str) { + return str + .replace(/[\\]/g, "\\\\") + .replace(/["]/g, '\\"') + .replace(/[/]/g, "\\/") + .replace(/[\b]/g, "\\b") + .replace(/[\f]/g, "\\f") + .replace(/[\n]/g, "\\n") + .replace(/[\r]/g, "\\r") + .replace(/[\t]/g, "\\t"); +} + // polyfill for node 4 function includes(array, val) { return array.indexOf(val) !== -1; @@ -218,7 +232,7 @@ function printExpression(path, options, print) { // use setting from options. need to figure out how this works w/ complex strings and interpolation // also need to figure out splitting long strings const quote = node.isDoubleQuote ? '"' : "'"; - return quote + node.value + quote; + return makeString(stringEscape(node.value), quote, true); } case "number": return node.value; diff --git a/tests/literals/__snapshots__/jsfmt.spec.js.snap b/tests/literals/__snapshots__/jsfmt.spec.js.snap index 7c41a9a47..03033a0b9 100644 --- a/tests/literals/__snapshots__/jsfmt.spec.js.snap +++ b/tests/literals/__snapshots__/jsfmt.spec.js.snap @@ -12,6 +12,15 @@ $silent = @$foo; $nowdoc = <<<'EOL' "test" foo EOL; +$newline = "hello\\nworld"; +$win_newline = "hello\\r\\nworld"; +$tab = "hello\\tworld"; +$backslash = "hello\\\\world"; +$slash = "hello/world"; +$single_quotes_with_double_quotes = '"hello world"'; +$single_quotes_with_single_quotes = '\\'hello world\\''; +$double_quotes_with_single_quotes = "'hello world'"; +$double_quotes_with_double_quotes = "\\"hello world\\""; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~