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
nodeto start practicing coding. - Use
String.prototype.split()andArray.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 stringmapStringwas 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.