convert new line /n to a line break in angular
Asked Answered
G

3

24

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;

Grubb answered 7/12, 2017 at 21:59 Comment(1)
Does this answer your question? angular - create a new line on HTMLWittenberg
P
64

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>
Powerless answered 12/6, 2018 at 9:47 Comment(0)
C
13

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>
Closer answered 1/10, 2021 at 12:11 Comment(0)
P
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'

Parable answered 7/12, 2017 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.