Normalize Line Endings

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28510{{"`Normalize Line Endings`"}} javascript/data_types -.-> lab-28510{{"`Normalize Line Endings`"}} javascript/arith_ops -.-> lab-28510{{"`Normalize Line Endings`"}} javascript/comp_ops -.-> lab-28510{{"`Normalize Line Endings`"}} end

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 the normalized version.
  • By default, the normalized version is set to '\r\n'.
  • To use a different normalized version, 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.

Other JavaScript Tutorials you may like