Mapping String Characters in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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.


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/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28481{{"`Mapping String Characters in JavaScript`"}} javascript/data_types -.-> lab-28481{{"`Mapping String Characters in JavaScript`"}} javascript/arith_ops -.-> lab-28481{{"`Mapping String Characters in JavaScript`"}} javascript/comp_ops -.-> lab-28481{{"`Mapping String Characters in JavaScript`"}} javascript/higher_funcs -.-> lab-28481{{"`Mapping String Characters in JavaScript`"}} end

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.

Other JavaScript Tutorials you may like