2

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:

  1. Client receives a string from the server
  2. This string is a JSON String and pretty long. Several sections in this string are divided by "\n"
  3. 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
  4. 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.
  5. How do I prevent the split() from breaking because of my regex?

I hope this explains my problem better.

12
  • 1
    we can't guess at the code that is doing this...where's your code? Commented Dec 20, 2014 at 21:13
  • David Thomas: edited post. Without code tag the replace() params were wrong... Commented Dec 20, 2014 at 21:15
  • 2
    Why do you need to re-escape all newlines? What is the purpose? Commented Dec 20, 2014 at 21:16
  • 2
    It sounds like the problem is not with your regex. The newline at the end is there from the start. When you double escape it, you're just double escaping a newline that already exists. Use String.trim() remove trailing whitespace at the beginning and end of the string (including newlines). Commented Dec 20, 2014 at 21:29
  • 1
    Better still would be to send the JSON string as an array from the start. It is JSON, after all. Commented Dec 20, 2014 at 21:33

1 Answer 1

1

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"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.