escaping - How to escape a JSON string containing newline characters using JavaScript? -
i have form json string in value having new line character. has escaped , posted using ajax call. can 1 suggest way escape string javascript. not using jquery.
take json , .stringify()
it. use .replace()
method , replace occurrences of \n
\\n
.
edit:
as far know of, there no well-known js libraries escaping special characters in string. but, chain .replace()
method , replace of special characters this:
var myjsonstring = json.stringify(myjson); var myescapedjsonstring = myjsonstring.replace(/\\n/g, "\\n") .replace(/\\'/g, "\\'") .replace(/\\"/g, '\\"') .replace(/\\&/g, "\\&") .replace(/\\r/g, "\\r") .replace(/\\t/g, "\\t") .replace(/\\b/g, "\\b") .replace(/\\f/g, "\\f"); // myescapedjsonstring ready post'ed server.
but that's pretty nasty, isn't it? enter beauty of functions, in allow break code pieces , keep main flow of script clean, , free of 8 chained .replace()
calls. let's put functionality function called, escapespecialchars()
. let's go ahead , attach prototype chain
of string
object, can call escapespecialchars()
directly on string objects.
like so:
string.prototype.escapespecialchars = function() { return this.replace(/\\n/g, "\\n") .replace(/\\'/g, "\\'") .replace(/\\"/g, '\\"') .replace(/\\&/g, "\\&") .replace(/\\r/g, "\\r") .replace(/\\t/g, "\\t") .replace(/\\b/g, "\\b") .replace(/\\f/g, "\\f"); };
once have defined function, main body of our code simple this:
var myjsonstring = json.stringify(myjson); var myescapedjsonstring = myjsonstring.escapespecialchars(); // myescapedjsonstring ready post'ed server
Comments
Post a Comment