From 8eed72694af39ca30c05ff31bd24cf44ac905005 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 4 May 2020 12:33:13 +0300 Subject: [PATCH] Add normalizeLineEndings --- snippets/normalizeLineEndings.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 snippets/normalizeLineEndings.md diff --git a/snippets/normalizeLineEndings.md b/snippets/normalizeLineEndings.md new file mode 100644 index 000000000..3ee8ff785 --- /dev/null +++ b/snippets/normalizeLineEndings.md @@ -0,0 +1,18 @@ +--- +title: normalizeLineEndings +tags: array,intermediate +--- + +Normalizes line endings in a string. + +Use `String.prototype.replace()` and a regular expression to match and replace line endings with the `normalized` version. +Omit the seconds argument, `normalized`, to use the default value of `'\r\n'`. + +```js +const normalizeLineEndings = (str, normalized = '\r\n') => str.replace(/\r?\n/g, normalized); +``` + +```js +splitLines('This\r\nis a\nmultiline\nstring.\r\n'); // 'This\r\nis a\r\nmultiline\r\nstring.\r\n' +splitLines('This\r\nis a\nmultiline\nstring.\r\n', '\n'); // 'This\nis a\nmultiline\nstring.\n' +```