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.

Output

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.

Was this post helpful?

Leave a Reply

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