5

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
  • 357
  • 2
  • 8
  • 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

3 Answers3

9

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
  • 395
  • 1
  • 2
  • 14
3

The solution from @adam has a bug, the new line character for a valid row will be removed as well. Example:

Input:

1
2

3
4

5
6

Result with: text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");

enter image description here

However using a similar regex will solve it: text.replace(/^\s*$(?:\r\n?|\n)/gm, "");

enter image description here

Complete example with plain JavaScript:

<textarea class="form-control" rows="10" oninput="validateValue(this)"></textarea>

<script>
    function validateValue(elem) {
        const value = elem.value;
        const newVal = value.replace(/^\s*$(?:\r\n?|\n)/gm, "");

        elem.value = newVal;
    }
</script>

Source:

https://stackoverflow.com/a/16369725/3850405

Ogglas
  • 62,132
  • 37
  • 328
  • 418
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
  • 176
  • 1
  • 1
  • 14