JavaScript: Create a new string with the results of calling a provided function on every character in the calling string
JavaScript fundamental (ES6 Syntax): Exercise-83 with Solution
Map Characters of String to New String
Write a JavaScript program to create an updated string with the results of calling a provided function on every character in the called string.
- Use String.prototype.split('') and Array.prototype.map() to call the provided function, fn, for each character in str.
- Use Array.prototype.join('') to recombine the array of characters into a string.
- The callback function, fn, takes three arguments (the current character, the index of the current character and the string mapString was called upon).
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
// Define the function 'mapString' to map each character of a string to a new character using a given function.
const mapString = (str, fn) =>
// Split the string into an array of characters, apply the function to each character along with its index, and join the resulting characters back into a string.
str.split('').map((c, i) => fn(c, i, str)).join('');
// Example usage:
console.log(mapString('Javascript exercises', c => c.toUpperCase())); // Outputs: "JAVASCRIPT EXERCISES"
Output:
JAVASCRIPT EXERCISES
Visual Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-83-1 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program that applies a transformation function to each character of a string and returns the new string.
- Write a JavaScript function that maps over a string’s characters, modifies them, and concatenates the results into a new string.
- Write a JavaScript program that converts a string by applying a provided callback to every character and joining the results.
Go to:
PREV : Map Array Values to Object.
NEXT : Generate Object Values by Function.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.