Let’s say, we have to write a function, say translate() that accepts a string as the first argument and any number of words after that.
The string will actually contain n $ signs like this −
This $0 is more $1 just a $2. Then there will be 3 strings which will replace the corresponding places.
For example −
If the function call is like this −
translate(‘This $0 is more $1 just a $2.’, ‘game’, ‘than’, ‘game’);
The output of the function should be −
This game is more than just a game.
This functionality is more or less like the template injecting in JavaScript.
Therefore, let’s write the code for this function −
We will use the String.prototype.replace() method here. We know that if we use a regex pattern to match all occurrences and use a function as the second parameter, it gets executed for each match. We will do exactly the same here.
The code for doing this will be −
Example
const str = 'This $0 is more $1 just a $2'; const translate = (str, ...texts) => { const regex = /\$(\d+)/gi; return str.replace(regex, (item, index) => { return texts[index]; }); }; console.log(translate(str, 'game', 'just', 'game'));
Output
The output in the console will be −
This game is more just just a game