Reputation:
I have a really long JSON String in JavaScript. It has several \n in it, which need to be escaped on clientside with:
replace(/\n/g, '\\n');
The Problem now is, that this replace()
adds an extra newline at the end of my JSON string which I don't want (result is that my split("\n") will produce an extra line which is empty and invalid. So, how can I properly handle this? How can I properly escape that String without breaking its structure while split("\n")
remains functional in the end?
Current string structure is something like: "testdata\ntestdata\ntestdata" etc.
EDIT: edit because I seem to not have given enough info:
replace(/\n/g, '\\n');
and after that perform split("\n") on it. That's all.I hope this explains my problem better.
Upvotes: 2
Views: 357
Reputation: 8472
There is no need for the replace
call if all you want to do is split a newline-separated string. The code sample below trims any leading or trailing whitespace (including newlines) and splits on \n
. Note that trim
was added in ECMAScript 5.1 and is not supported in some older browsers. See this MDN page for more information.
function splitNewlineSeparatedString (s) {
return s.trim().split("\n");
}
console.log(splitNewlineSeparatedString("testdata\ntestdata\ntestdata\n\n\n"));
Upvotes: 1