Introduction
In this lab, we will explore how to normalize line endings in a string using JavaScript. We will use the String.prototype.replace() method along with a regular expression to match and replace line endings with the normalized version. Additionally, we will learn how to omit the second argument to use the default value and see examples of how the function works in practice.
Function to Normalize Line Endings
To normalize line endings in a string, you can use the following function.
const normalizeLineEndings = (str, normalized = "\r\n") =>
str.replace(/\r?\n/g, normalized);
- Use
String.prototype.replace()with a regular expression to match and replace line endings with thenormalizedversion. - By default, the
normalizedversion is set to'\r\n'. - To use a different
normalizedversion, pass it as the second argument.
Here are some examples:
normalizeLineEndings("This\r\nis a\nmultiline\nstring.\r\n");
// 'This\r\nis a\r\nmultiline\r\nstring.\r\n'
normalizeLineEndings("This\r\nis a\nmultiline\nstring.\r\n", "\n");
// 'This\nis a\nmultiline\nstring.\n'
Summary
Congratulations! You have completed the Normalize Line Endings lab. You can practice more labs in LabEx to improve your skills.