EN
JavaScript - remove new line characters from string
6
points
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