Table of Contents
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.
1 2 3 4 5 6 |
const text = 'Line 1 \n Line 2'; console.log(text) const result = text.replace(/[\n]/g, '\\n') console.log(result); |
Output
1 2 3 4 5 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.