[Fixed] Remove \r\n from innerHTML that comes as an API response in Angular 9

Issue

I am trying to display HTML text that I am getting as an API response. The API response is like this

    <p> Some text </p>
    \r\n
    <p> Some text </p>
    \r\n
    <p> Some text </p>
    \r\n
    <p> Some text </p>

and it is getting displayed like this

    Some text
    \r\n
    Some text
    \r\n    
    Some text
    \r\n    
    Some text

I tried all the ways I could find on the internet to remove \r\n from getting displayed but nothing worked for me. Can anyone please suggest something.

\r\n is not a string it is a part of the html that I am receiving in the API response. That might be the reason

string.replace 

doesnot work here.

Solution

This should do the trick. We run this as two separate string replacements. Because there are multiple occurrences, we run them as regex expressions with the global flag /g. First we replace any instances of \r and then we replace any instances of \n which will also replace the line breaks between the p tags. Let me know if this works for you!

let input =
`<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>`;

let output = input.replace(/\r/g, '').replace(/\n/g, '');

console.log(output);

If you only want to remove the instances of \r\n together and not remove the line breaks between your p tags, this should work as well:

let input =
`<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>`;

let output = input.replace(/\r\n/g, '');

console.log(output);

That will leave an empty line between each of your p tags. However, if you want the p tags on separate lines but don’t want an empty space between them, then we just run the same replacement with an extra \n after the \r\n to replace the \r and then the two line breaks following it (\r\n\n):

let input =
`<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>
\r\n
<p> Some text </p>`;

let output = input.replace(/\r\n\n/g, '');

console.log(output);

Leave a Reply

(*) Required, Your email will not be published