Escape new line in JavaScript

In this post, we will see how to escape new line in JavaScript.

There is no well known JavaScript library which can escape all special characters in String.

Escape new line in JavaScript

To escape new line in JavaScript:

  • Use replace() method with regular expression /[\n]/g as first parameter and \\n string as second parameter.

Let’s see with the help of example.

const text = 'Line 1 \n Line 2';
console.log(text)
const result = text.replace(/[\n]/g, '\\n')
console.log(result);

Output

Line 1 
 Line 2
Line 1 \n Line 2

As you can see, we have successfully escaped new line using replace() method.

Conclusion

To escape JSON string containing newline characters, chain replace() method with all required special characters which you want to escape.

That’s all about how to escape JSON string containing newline characters in JavaScript.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.