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:
- Client receives a string from the server
- This string is a JSON String and pretty long. Several sections in this string are divided by "\n"
- On Clientside I need to perform split("\n") on the string to split it into exactly 50 rows. However I get 51, because an extra \n is added at the end after I escape the string
- So, I only receive the data in e.data, then perform
replace(/\n/g, '\\n');and after that perform split("\n") on it. That's all. - How do I prevent the split() from breaking because of my regex?
I hope this explains my problem better.
String.trim()remove trailing whitespace at the beginning and end of the string (including newlines).