I have to form a JSON string in which a value is having new line character. This has to be escaped and then posted using AJAX call. Can any one suggest a way to escape the string with JavaScript. I am not using jQuery.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Take your JSON and
.stringify()it. Then use the.replace()method and replace all occurrences of\nwith\\n.EDIT:
As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the
.replace()method and replace all of the special characters like this:But that’s pretty nasty, isn’t it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained
.replace()calls. So let’s put that functionality into a function called,escapeSpecialChars(). Let’s go ahead and attach it to theprototype chainof theStringobject, so we can callescapeSpecialChars()directly on String objects.Like so:
Once we have defined that function, the main body of our code is as simple as this: