Languages
[Edit]
EN

JavaScript - remove new line characters from string

6 points
Created by:
ArcadeParade
666

In this short article, we are going to show how to remove all new line characters from string using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const EXPRESSION = /\r\n|\n\r|\n|\r/g;  // expression symbols order is very important

const text = 'line-1\n' +
             'line-2\n' +
             'line-3';

const result = text.replace(EXPRESSION, ' ');

console.log(result);  // line-1 line-2 line-3

 

Reusable function

// ONLINE-RUNNER:browser;

const EXPRESSION = /\r\n|\n\r|\n|\r/g;  // expression symbols order is very important

const removeNewlines = (text, replacement = '') => text.replace(EXPRESSION, replacement);


// Usage example:

const text = 'line-1\n' +
             'line-2\r' +
             'line-3\r\n' +
             'line-4\n\r' +
             'line-5';

console.log(removeNewlines(text));       // line-1line-2line-3line-4line-5
console.log(removeNewlines(text, ' '));  // line-1 line-2 line-3 line-4 line-5
console.log(removeNewlines(text, '+'));  // line-1+line-2+line-3+line-4+line-5
console.log(removeNewlines(text, '/'));  // line-1/line-2/line-3/line-4/line-5

 

See also

  1. JavaScript - string newline character

  2. JavaScript - split string by new line character

Alternative titles

  1. JavaScript - remove line breaks in string
  2. JavaScript - remove newline characters from string
  3. JavaScript - remove line breaks from string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join