2

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!

2
  • 1
    Are you using Jquery ? Commented Mar 28, 2021 at 17:22
  • 2
    str.replace(/\\n/g, "<br>") Commented Mar 28, 2021 at 17:24

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Very great explanation and works now perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.