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:
xxxxxxxxxx
1
const EXPRESSION = /\r\n|\n\r|\n|\r/g; // expression symbols order is very important
2
3
const text = 'line-1\n' +
4
'line-2\n' +
5
'line-3';
6
7
const result = text.replace(EXPRESSION, ' ');
8
9
console.log(result); // line-1 line-2 line-3
xxxxxxxxxx
1
const EXPRESSION = /\r\n|\n\r|\n|\r/g; // expression symbols order is very important
2
3
const removeNewlines = (text, replacement = '') => text.replace(EXPRESSION, replacement);
4
5
6
// Usage example:
7
8
const text = 'line-1\n' +
9
'line-2\r' +
10
'line-3\r\n' +
11
'line-4\n\r' +
12
'line-5';
13
14
console.log(removeNewlines(text)); // line-1line-2line-3line-4line-5
15
console.log(removeNewlines(text, ' ')); // line-1 line-2 line-3 line-4 line-5
16
console.log(removeNewlines(text, '+')); // line-1+line-2+line-3+line-4+line-5
17
console.log(removeNewlines(text, '/')); // line-1/line-2/line-3/line-4/line-5