Mapping String Characters in JavaScript

Beginner

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

Introduction

In this lab, we will explore the mapString function in JavaScript. This function allows us to create a new string by applying a provided function to every character in a given string. We'll learn how to use String.prototype.split(), Array.prototype.map(), and Array.prototype.join() to implement mapString and see how it can be useful in various scenarios.

Function to Map Characters in a String

To use this function to map characters in a string, follow these steps:

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use String.prototype.split() and Array.prototype.map() to call the provided function, fn, for each character in the given string.
  • Use Array.prototype.join() to recombine the array of characters into a new string.
  • The callback function, fn, takes three arguments: the current character, the index of the current character, and the string mapString was called upon.

Here's the function code:

const mapString = (str, fn) =>
  str
    .split("")
    .map((c, i) => fn(c, i, str))
    .join("");

Example usage:

mapString("lorem ipsum", (c) => c.toUpperCase()); // 'LOREM IPSUM'

Summary

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