23

I have a string which contain new line character /n. Trying to display

the string. Instead of taking the /n as new line, it displays '/n' as text.

   $scope.myOutput = " Hello /n"

    {{ myOutput | textFormat }}

Required -> Hello (on html page)

Tried :

 app.filter('textFormat', function() {
    return function(x) {
      return x.replace(/\\n/g, '<br/>');
   }

Tried css styles like white-space: pre;

Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39
  • Does this answer your question? [angular - create a new line on HTML](https://stackoverflow.com/questions/44410095/angular-create-a-new-line-on-html) – Vega Mar 21 '23 at 20:15

3 Answers3

62

This does not replace it, but you can use the CSS attribute white-space: pre-line; to render the \n in the browser: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

div {
  white-space: pre-line;
}
<div>Foo
   Bar
       Baz     Foo
     Bar
 


     
  Baz
</div>
Tim Schoch
  • 5,764
  • 2
  • 15
  • 20
11

in Angular you can easy convert text to the original format by entering it like so:

component:

this.myText = 'This is line one\nThis is line 2\nAnd here is 3'

html:

<div [innerText]='myText'></div>
Maurice Buiten
  • 174
  • 1
  • 5
0

1 - rewrite your filter next way:

.filter('textFormat', function() {
    return function (x) {
      return x.replace(new RegExp('\/n', 'g'), '<br/>');
    }
 })

2 - in your html you should use the next syntax:

<span ng-bind-html="myOutput | textFormat"></span>

Where myOutput is $scope.myOutput = ' Hello /n'

Vadym Shashkov
  • 118
  • 2
  • 14