Avoid unnecessary spaces in textarea with standard text

Asked

Viewed 752 times

1

Situation: I have an element textarea which has standard text, which can then be changed by the user. The text has multiple lines.

Problem: Text takes into account the indentation spaces of the source code.

Pseudo-code:

    <html>
        <body>
            <textarea>Olá,
            
            Isto é um teste.</textarea>
        </body>
    </html>

When rendering the page, the text inside the element textarea appears like this:

Hello,

           This is a test.

Is there any way to avoid that?

1 answer

3


Via javascript, you could do it this way:

$(function() {
  var textareas = $('textarea.clean');
  $.each(textareas, function(key, value) {
    $(this).val($(this).val().replace(/[ ]+/g, ' ').replace(/^[ ]+/m, ''));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea class="clean" rows="5">Olá,

            Isto é um teste.</textarea>

<textarea rows="5">Olá,

            Isto é um teste.</textarea>

  • Should the line breaks not be maintained, generating an output as Olá,\n\nIsto é um teste.?

  • Anderson, yes, just adapt the regular expression. s refers to any space, it considers line break and white spaces. Just put " " space that would work.

  • Because I believe that’s the point of the question: just remove the indentation, not the line breaks.

  • 1

    Corrected! Thank you Anderson, I really agree with you. Now, just putting space would not work because the line below would have 1 space, then put a second replace to solve this problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.