Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active June 25, 2022 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/d4b700385970ce6e1a70e49ffa0dff6a to your computer and use it in GitHub Desktop.
Save rauschma/d4b700385970ce6e1a70e49ffa0dff6a to your computer and use it in GitHub Desktop.
//========== .split() with lookbehind ==========
// Downside: Safari doesn’t support lookbehind
import * as assert from 'node:assert/strict';
const RE_SPLIT_AFTER_EOL = /(?<=\r?\n)/;
function splitLinesWithEols1(str) {
return str.split(RE_SPLIT_AFTER_EOL);
}
assert.deepEqual(
splitLinesWithEols1('there\nare\r\nmultiple\nlines'),
['there\n', 'are\r\n', 'multiple\n', 'lines']
);
assert.deepEqual(
splitLinesWithEols1('first\n\nthird'),
['first\n', '\n', 'third']
);
assert.deepEqual(
splitLinesWithEols1('EOL at the end\n'),
['EOL at the end\n']
);
assert.deepEqual(
splitLinesWithEols1('\r\n'),
['\r\n']
);
assert.deepEqual(
splitLinesWithEols1(''),
['']
);
//========== .indexOf() ==========
import * as assert from 'node:assert/strict';
function splitLinesWithEols2(str) {
if (str.length === 0) return [''];
const lines = [];
let prevEnd = 0;
while (prevEnd < str.length) {
const newlineIndex = str.indexOf('\n', prevEnd);
// If there is a newline, it’s included in the line
const end = newlineIndex < 0 ? str.length : newlineIndex+1;
lines.push(str.slice(prevEnd, end));
prevEnd = end;
}
return lines;
}
assert.deepEqual(
splitLinesWithEols2('there\nare\r\nmultiple\nlines'),
['there\n', 'are\r\n', 'multiple\n', 'lines']
);
assert.deepEqual(
splitLinesWithEols2('first\n\nthird'),
['first\n', '\n', 'third']
);
assert.deepEqual(
splitLinesWithEols2('EOL at the end\n'),
['EOL at the end\n']
);
assert.deepEqual(
splitLinesWithEols2('\r\n'),
['\r\n']
);
assert.deepEqual(
splitLinesWithEols2(''),
['']
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment