Last active
October 29, 2021 01:01
-
-
Save Craphtex/faff399967e7f508ba92f47543e1a611 to your computer and use it in GitHub Desktop.
JavaScript function for replaces {n} in a string with the nth following parameter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replaces {n} in a string with the nth following parameter. | |
const format = (text, ...values) => text.replace(/{([0-9]*)}/g, (m, i) => values[i] || m) | |
// Example 1 | |
console.log(format('Hello {0}! How\'s your {1}?', 'my dear', 'day been')) | |
// Output: Hello my dear! How's your day been? | |
// Example 2 | |
const list = ['the city', 'train', 'speed', 'convenient'] | |
console.log(format("I went to {0} by {1}.", ...list)) | |
// Output: I went to the city by train. | |
console.log(format("The {2} of the {1} makes it {3}.", ...list)) | |
// Output: The speed of the train makes it convenient. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment