1

When I copy and paste text into a textarea, is there a way to ignore if there's line breaks and whitespaces?

For example, When I highlight text below and copy paste into the textarea:

abcdef,
ghijkl,
mnopqrs

I want them to be in the text area:

abcdef,ghijkl,mnopqrs

ignore any whitespaces and line breaks.

davis
  • 340
  • 1
  • 4
  • 17

1 Answers1

1

You can use a paste event or input event (which covers paste and key events) and a regex to remove line break characters.

For explanation of the regex used see https://stackoverflow.com/a/10805198/1175966

document.querySelector('textarea').addEventListener('input', function(){
   this.value = this.value.replace(/(\r\n|\n|\r)/gm, "");
})
<textarea></textarea>

<pre>
abcdef,
ghijkl,
mnopqrs
</pre>
charlietfl
  • 170,828
  • 13
  • 121
  • 150