Script this considers enter as white space

2

I made a script to remove whitespace 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 with this code is that it considers the enter that I give inside a textarea as white space too and it leaves everything on the line line when I finish typing, eg

I want it to look like this:

Testing:
1- Testing 2- Testing 3- Test

But here the script goes and leaves everything on the same line, considering the space as well, follow the example:

Testing: 1- Test 2- Test 3- Test

I want you to remove the whitespace, but not enter as blank, to continue giving this line break normally.

    
asked by anonymous 16.02.2017 / 15:04

1 answer

3

You can use unicode of whitespace to specify better:

$(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>

Theproblemisthat\sconsidersnotonly'space'aswhitespace,butendsupinterpretinglinebreaksaswell.Usingunicodeitwillonlyconsiderspacesinthespacebar.

Youcanreadmoreabout\s here .

    
16.02.2017 / 15:16