Reputation: 271
I have the following code like
<div id="profile_description">
<p>Some Text with\nNew Line</p>
</div>
Here is my Javascript code for replace \n to < br >console.log($('#profile_description_field').html());
var str = $('#profile_description').html();
console.log(str);
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
console.log(str);
The output is always Some Text with\nNew Line
What I doing wrong here? I have tried so many things ... I hope you have a idea. Thank you so much!
Upvotes: 2
Views: 54
Reputation: 943097
Your text doesn't have a new line in it, it has a slash character followed by an n.
It works fine if you have a new line in the HTML.
var str = $('#profile_description').html();
console.log(str);
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="profile_description">
<p>Some Text with
New Line</p>
</div>
If you want to deal with your original HTML then you'll need to replace a slash followed by a the letter n, which means you have to escape the slash.
var str = $('#profile_description').html();
console.log(str);
str = str.replace(/\\n/g, '<br>');
console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="profile_description">
<p>Some Text with\nNew Line</p>
</div>
Upvotes: 2