Viết hàm translate() nhận chuỗi đầu tiên và bất kỳ số từ nào sau đó. Chuỗi chứa n ký tự $ như: This $0 is more $1 just a $2. Sẽ có 3 chuỗi thay thế cho các vị trí tương ứng.
Ví dụ: translate('This $0 is more $1 just a $2.', 'game', 'than', 'game') => This game is more than just a game.
Chức năng này giống template injection. Dùng String.prototype.replace() với regex và function callback.
Ví dụ
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'));Kết quả
Đầu ra trong console sẽ là:
This game is more just just a game