JavaScript: Replace New Line Characters in a textarea with Spaces

To replace new line characters in a textarea with spaces we can use JavaScript and RegEx.

 

Let's create a textarea element with an ID attribute in HTML and a JavaScript function that will replace all the new lines with spaces and set the result as the new textarea value.

 

<textarea id="foo"></textarea>
document.getElementById('foo').addEventListener('keyup', function removeNewLines() {

  var text = this.value.replace(/\s/gm, ' ');

  this.value = text;
});

 

 

The above example works by using a keyup event listener to trigger a function that gets the value of the textarea and removes all new lines from it with the JavaScript replace() method before updating the value.

text