Keeping newline n as is in JavaScript object


Keeping newline n as is in JavaScript object



I want to keep string values in my insert object as is



This works fine, the n is kept


{insert: "erferferfnerferferf"}



This


{insert: "nnn"}



And this becomes a problem


{insert: "n"}



it makes the string like this


{insert: "


"}



I want the string to keep the "nnn" rather than becoming a bunch of new lines





try using .trim(), it may solve your problem.
– Raghav Garg
Jul 2 at 9:49


.trim()





Possible duplicate of How to escape special characters in building a JSON string?
– Islam Elshobokshy
Jul 2 at 9:51





JSON.stringify("nnn").slice(1, -1)
– Keith
Jul 2 at 9:52


JSON.stringify("nnn").slice(1, -1)





Simply put before n. {insert: "nnn"}
– Abhay Prince
Jul 2 at 9:54




1 Answer
1



Use .replace() to replace n with n. If you leave n in the variable, it is interpreted as a next line character. So, just replace it with n, thus effectively making it + n.


.replace()


n


n


n


next line character


n



Here is an example to illustrate what I'm on about.




string = "javascriptn";
console.log(string.replace("n","n"));
data = {insert:string.replace("n","n")};
console.log("From Object: "+data['insert']);

string = "n"
console.log(string.replace("n","n"));
data = {insert:string.replace("n","n")};
console.log("From Object: "+data['insert']);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages