Script this considers enter as white space

Asked

Viewed 243 times

2

I made a script to remove blanks from a string inside a TEXTAREA or INPUT, follow the code just below:

  input = 'input[type="text"]:not(.inputData), textarea';

  $(document).on('blur', input, function(){
    console.log('blur');
    $(this).val($(this).val().replace(/\s\s+/g, ' '));
    $(this).val($(this).val().replace(/^\s+|\s+$/g, ''));
  });

The problem of this code is that it considers the enter that I give inside a textarea as white space as well and it leaves everything in the line Mensa when finished typing, example:

I want you to stay like this:

Testing:
1- Testing
2- Testing
3- Testing

But then the script goes and leaves everything in the same line so considering the between as space also, follows the example:

Testing: 1-Test 2-Test 3-Test

I want you to take out the blanks, but without considering enter as white space, to continue giving this line break normally.

1 answer

3


You can use the unicode of whitespace to better specify:

$(this).val($(this).val().replace(/\u0020+/g, ' '));

Example:

input = 'input[type="text"]:not(.inputData), textarea';

$(document).on('blur', input, function() {
    $(this).val($(this).val().replace(/\u0020+/g, ' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

The problem is that the \s considers not only 'space' but whitespace, and ends up interpreting line breaks as well. Using the unicode it will only consider space bar spaces.

You can read more about the \s here.

  • 1

    It wouldn’t be easy to figure that out. Thanks ! I’ll give it a read on.

Browser other questions tagged

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