Loop through array and edit string JavaScript

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 template injection in JavaScript.

How It Works

We will use the String.prototype.replace() method with a regular expression. When we use a regex pattern to match all occurrences and use a function as the second parameter, it gets executed for each match.

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', 'than', 'game'));

Output

This game is more than just a game

Alternative Approach Using For Loop

You can also use a traditional for loop approach to iterate through the replacements:

function translateWithLoop(str, ...texts) {
    let result = str;
    for (let i = 0; i < texts.length; i++) {
        result = result.replace('$' + i, texts[i]);
    }
    return result;
}

const template = 'Hello $0, welcome to $1!';
console.log(translateWithLoop(template, 'John', 'JavaScript'));

Output

Hello John, welcome to JavaScript!

Handling Multiple Occurrences

If you need to handle cases where the same placeholder appears multiple times:

const translateAll = (str, ...texts) => {
    const regex = /\$(\d+)/g;
    return str.replace(regex, (match, index) => {
        return texts[parseInt(index)] || match;
    });
};

const message = 'The $0 loves $0 and $1';
console.log(translateAll(message, 'cat', 'fish'));

Output

The cat loves cat and fish

Conclusion

Using String.replace() with regular expressions provides an elegant solution for template string replacement. The spread operator (...texts) allows handling any number of replacement arguments dynamically.

Updated on: 2026-03-15T23:18:59+05:30

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements