Alexander Mills
Alexander Mills

Reputation: 100000

String within a string can't be split by newline char

I don't really know why this is the case -

a string literal like the following is ""double-encoded"":

" => Suman => fatal error in suite with path=\"/Users/amills001c/WebstormProjects/oresoftware/suman/test/build-tests/test6.js\"\n (note: You will need to transpile your test files if you wish to use ES7 features)" => error => "SyntaxError: Unexpected reserved word\n    at exports.runInThisContext (vm.js:53:16)\n    at Module._compile (module.js:373:25)\n    at Object.Module._extensions..js (module.js:416:10)\n    at Module.load (module.js:343:32)\n    at Function.Module._load (module.js:300:12)\n    at Module.require (module.js:353:17)\n    at require (internal/module.js:12:17)\n    at Domain.<anonymous> (/Users/amills001c/WebstormProjects/oresoftware/suman/lib/run-child.js:33:5)\n    at Domain.run (domain.js:228:14)\n    at Object.<anonymous> (/Users/amills001c/WebstormProjects/oresoftware/suman/lib/run-child.js:32:3)"

the reason it's double encoded is because it was created like:

var str = "foo" + JSON.stringify(bar) + "baz";

is there a good reason why I won't be able to then split the resulting string with String(str).split('\n') ? Seems to be the case, just curious as to why that is.

Upvotes: 0

Views: 39

Answers (1)

Petr
Petr

Reputation: 6269

The problem is not in double-quoting. The issue is that JSON.stringify escapes all the special characters in the string. So, basically your \n in the resulting string is not a new-string character, but two characters "\" and "n". To achieve what you want use str.split('\\n')

Upvotes: 1

Related Questions