Indent String Formatting in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into the indentString function in JavaScript. This function allows us to easily indent each line in a given string by a specified amount. With this function, we can format strings for better readability and organization in our code.


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-28387{{"`Indent String Formatting in JavaScript`"}} javascript/data_types -.-> lab-28387{{"`Indent String Formatting in JavaScript`"}} javascript/arith_ops -.-> lab-28387{{"`Indent String Formatting in JavaScript`"}} javascript/comp_ops -.-> lab-28387{{"`Indent String Formatting in JavaScript`"}} end

A Function to Indent Strings in JavaScript

To add indentation to each line in a given string, you can use the indentString() function in JavaScript. This function takes three arguments: str, count, and indent.

  • The str argument represents the string you want to indent.
  • The count argument determines how many times you want to indent each line.
  • The indent argument is optional and represents the character you want to use for indentation. If you don't provide it, the default value is a single space character (' ').

Here is the code for the indentString() function:

const indentString = (str, count, indent = " ") =>
  str.replace(/^/gm, indent.repeat(count));

To use this function, simply call it with the desired arguments. Here are some examples:

indentString("Lorem\nIpsum", 2); // '  Lorem\n  Ipsum'
indentString("Lorem\nIpsum", 2, "_"); // '__Lorem\n__Ipsum'

In the first example, indentString('Lorem\nIpsum', 2) returns ' Lorem\n Ipsum', which means that each line of the input string has been indented two times with space characters.

In the second example, indentString('Lorem\nIpsum', 2, '_') returns '__Lorem\n__Ipsum', which means that each line of the input string has been indented two times with underscore characters ('_').

Summary

Congratulations! You have completed the Indent String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like