Word Wrap String

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the concept of string manipulation in JavaScript. Specifically, we will be focusing on the wordWrap function which allows us to wrap a string to a given number of characters using a string break character. By the end of this lab, you will have a better understanding of how to manipulate strings in JavaScript to achieve specific formatting requirements.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced 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`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28697{{"`Word Wrap String`"}} javascript/data_types -.-> lab-28697{{"`Word Wrap String`"}} javascript/arith_ops -.-> lab-28697{{"`Word Wrap String`"}} javascript/comp_ops -.-> lab-28697{{"`Word Wrap String`"}} javascript/template_lit -.-> lab-28697{{"`Word Wrap String`"}} end

Instructions for Word Wrap String

To practice coding, open the Terminal/SSH and type node.

This code wraps a string to a given number of characters using a string break character. To use it, follow these steps:

  1. Use String.prototype.replace() and a regular expression to insert a given break character at the nearest whitespace of max characters.
  2. If you don't want to use the default value of '\n' for the third argument, br, you can omit it and provide your own character.

Here is the code:

const wordWrap = (str, max, br = "\n") =>
  str.replace(
    new RegExp(`(?![^\\n]{1,${max}}$)([^\\n]{1,${max}})\\s`, "g"),
    "$1" + br
  );

And here are some examples of how to use it:

wordWrap(
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.",
  32
);
// 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit.\nFusce tempus.'

wordWrap(
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.",
  32,
  "\r\n"
);
// 'Lorem ipsum dolor sit amet,\r\nconsectetur adipiscing elit.\r\nFusce tempus.'

Summary

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

Other JavaScript Tutorials you may like