AngularJS – Remove \n from data

All we need is an easy explanation of the problem, so here it is.

What is the best way to catch and format the “\n\n” inside of text being passed from the server to display line breaks?
Fiddle is here: http://jsfiddle.net/nicktest2222/2vYBn/

$scope.data = [{
    terms: 'You agree to be bound be the terms of this site. \n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus lectus ac nunc malesuada, fringilla feugiat nibh rhoncus. Vestibulum adipiscing mi in est consectetur, vitae facilisis nulla tristique. Nam eu ante egestas, ultricies tellus eu, suscipit neque.\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum et ligula non tellus semper iaculis eget vestibulum metus. Nunc aliquam eros sit amet sapien posuere, ac hendrerit risus ultricies. Vivamus nec enim sed eros placerat pulvinar a quis dui.',
    agreed: false
}];

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can also use a custom filter to replace \n to <br>.

<p ng-bind-html-unsafe="data[0].terms | nl2br"></p>

And the filter.

angular.module('myApp', [])
  .filter('nl2br', function(){
      return function(text) {
           return text ? text.replace(/\n/g, '<br>') : '';
      };
});

** EDIT/UPDATE – 2014-12-10 **

Since new versions of Angular removed ng-bind-html-unsafe @Tamlyn answer is now the best answer. I just changed the way $sce got injected into the function for speed purpose.

HTML

<p ng-bind-html="data[0].terms | nl2br"></p>

JS

.filter('nl2br', ['$sce', function ($sce) {
    return function (text) {
        return text ? $sce.trustAsHtml(text.replace(/\n/g, '<br/>')) : '';
    };
}]);

jsFiddle

Method 2

Angular 1.2 removed ng-bind-html-unsafe so here’s an updated solution.

The HTML:

<p ng-bind-html="data[0].terms | nl2br"></p>

And the JS:

.filter('nl2br', function ($sce) {
    return function (text) {
        return text ? $sce.trustAsHtml(text.replace(/\n/g, '<br/>')) : '';
    };
})

Method 3

You can use ngBindHtmlUnsafe directive, with terms: '... <br/><br/>...'

<p ng-bind-html-unsafe='data[0].terms'></p>

You can either send the html to the AngularJS, or send the string with \n and replace it with <br/> in AngularJS’s controller. Either way should work. Hope it helps.

Demo

Method 4

You have the following options:

  • use pre tag and keep \n
  • use white-space:pre css rule and keep \n
  • replace \n with <br> tag as @sza offered.

Method 5

If ‘text’ is null it returns an error, I added:

.filter('nl2br', function(){
    return function(text){
        return text?text.replace(/\n/g, '<br/>'):'';
    };
});

Method 6

You can create a simple filter that will split your string into paragraphs:

.filter('lines', function() {
    return function(text) {
      return angular.isString(text) ? text.split(/\n/g) : text;
    }
  })   

And use it in view to display them:

<p ng-repeat="paragraph in myText | lines track by $index">{{ paragraph }}</p>

There is no need for bind-html-unsafe.

See this in action in the snippet:

angular.module('module', [])
  .filter('lines', function() {
    return function(text) {
      return angular.isString(text) ? text.split(/\n/g) : text;
    }
  })
  .controller('MyCtrl', function($scope) {
    $scope.myText = "First line\nSecondLine\nThird line\n\n\n\n\nAlone line";
  });
p {
  min-height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module">
  <div ng-controller="MyCtrl">
    <p ng-repeat="paragraph in myText | lines track by $index">{{ paragraph }}</p>
  </div>
</div>

This is not my idea but I can’t find the source right now

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply