Textarea string: limit to 1 empty line at a time

I have a multivalue textarea where each line represents one array value.

I want to remove empty lines if they exist when enter is pressed(im doing this through angular directive not on keypress). The expected result is that only one empty line can exist at the time.

I am trying to use textareStringValue.replace(/n{2,}/gm, 'n'). But depending on the position of the new line and the text caret position the replace condition changes.

Can this be done with one .replace(regExp)?

  app.directive('noTwolines', function () {

  return {
      restrict: 'A',
      require: '?ngModel',

      link: function (scope, element, attrs, ngModel) {
          if (!ngModel) return;
          ngModel.$parsers.unshift(function (inputValue) {
              var digits = inputValue;
              var textarea= document.getElementById("textarea");
              var val = textarea.value;
              var caretPos = val.slice(0, textarea.selectionStart).length;
              console.log(val.slice(0, textarea.selectionStart).length);

              if(caretPos === inputValue.length){
                console.log('enter from end');
                digits=  inputValue.replace(/n{2,}/gm, 'n');
              if(caretPos < inputValue.length && inputValue.indexOf('nn') != -1){
                digits=  inputValue.replace(/n{3,}/gm, 'n');

              return digits;



Source: regex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.