EN
TypeScript - universal new lines splitting symbol example
0 points
In this article, we're going to have a look at the problem of how to universal way to split strings to separate lines in TypeScript, when we work on mixed newline text.
The below approach works with all operating systems:
xxxxxxxxxx
1
const LINE_EXPRESSION: RegExp = /\r\n|\n\r|\n|\r/g; // expression symbols order is very important
2
3
const text: string = 'line 1\n' + 'line 2\r' + 'line 3\r\n' + 'line 4\n\r' + 'line 5';
4
5
const lines: string[] = text.split(LINE_EXPRESSION);
6
7
console.log(lines);
Output:
xxxxxxxxxx
1
[ 'line 1', 'line 2', 'line 3', 'line 4', 'line 5' ]