1

I have a JSON string for example:

"\nReferenceNo:20,Amount:100\nReferenceNo:30,Amount:200" 

now i want to replace \n with <br /> HTML tag. My code is given below

 var myJSONString = JSON.stringify(d.otherDetails);
 result=myJSONString.replace(RegExp("\n","g"), "<br />");
 alert(result);

How to do that?

Thanks in advance

5
  • "\n" is a new line character. Different OSes display them differently (e.g., Windown requires \r\n). Where are you trying to display it? In the browser? Commented Jul 12, 2014 at 13:47
  • I've taken the liberty of editing your question to fix references to line feeds. Most of them were wrong yet I don't think that fact affects the question (thus my edit). Commented Jul 12, 2014 at 13:50
  • BTW, I strongly suggest you edit data before encoding or after decoding. Fiddling with serialised data structures is seldom a good idea. Commented Jul 12, 2014 at 13:51
  • Right, he didn't specify he wanted to display the line break in the browser. It could have been the console or somewhere else on the server. Commented Jul 12, 2014 at 13:52
  • @vol7ron i want to dispaly it in browser Commented Jul 12, 2014 at 14:04

2 Answers 2

1

Try this:

result = myJSONString.replace(RegExp("\\n","g"), "\n");

It's because HTML is not interpreted in JSON and \n matches an actual new line, but \n matches an backslash followed by a n character.

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

Comments

0

Pattern:

\\n

Replacement string:

\n

DEMO

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.