user1648409
user1648409

Reputation:

Properly escape newlines in javascript json strings

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.

Upvotes: 2

Views: 357

Answers (1)

Drew Gaynor
Drew Gaynor

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

Related Questions