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]/gas first parameter and\\nstring 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.