3

First, I've tried all possible solutions that I've found here or Google, but no one seems to work for me.

To be clear, I need to remove every empty lines from a text area. This is what I've done so far:

<textarea name="text" class="form-control" rows="14" id="text" placeholder="Here goes our query" ></textarea>


$(document).ready(function () {
    $('#text').focusout(function () {
        var text = $('#text').val();

        text.replace(/(\r\n|\n|\r)/gm,"");

        alert('done');
    });
});

I get successful alert on end, but those empty lines are still there. Is regexp correct ? My knowledge for js is not that big, so I need help :(

fugitive
  • 337
  • 2
  • 6
  • 26
  • 1
    See [*JavaScript: how to use a regular expression to remove blank lines from a string?*](http://stackoverflow.com/questions/16369642/javascript-how-to-use-a-regular-expression-to-remove-blank-lines-from-a-string) and [*Can't remove empty line break in textarea with Javascript replace method*](http://stackoverflow.com/questions/13205169/cant-remove-empty-line-break-in-textarea-with-javascript-replace-method). Also, [*jquery text().replace('','') not working*](http://stackoverflow.com/questions/28025944/jquery-text-replace-not-working). – Wiktor Stribiżew Aug 01 '16 at 12:18

2 Answers2

8

http://www.w3schools.com/jsref/jsref_replace.asp

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

So you are not actually changing the textarea value.

You can use

$(document).ready(function () {
    $('#text').focusout(function () {
        var text = $('#text').val();
        text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
        $(this).val(text);
    });
});

The regex is from here.

Community
  • 1
  • 1
adam
  • 375
  • 1
  • 2
  • 13
2

You can try like this:

$(document).ready(function () {
    $('#text').focusout(function () {
        var text = $('#text').val();

        var modifiedtext=text.replace(/ /g, "");
         $(this).val(modifiedtext);
        alert('done');

    });
});
Dil85
  • 166
  • 1
  • 1
  • 12