Skip to content

Instantly share code, notes, and snippets.

@pramodmg
Created December 5, 2017 06:44
Show Gist options
  • Save pramodmg/629ded676b1fc634b9242868bbd63973 to your computer and use it in GitHub Desktop.
Save pramodmg/629ded676b1fc634b9242868bbd63973 to your computer and use it in GitHub Desktop.
Replacing an array with an index values of the String
// es6 syntax
var arr = ["a","b","c"];
var str = "Hello {1} is a friend of {2} and {3}";
var result_es6 = arr.reduce((str_data, replacement, idx) => {
return str_data.replace(`{${idx + 1}}`, replacement)
}, str);
console.log(result_es6); // "Hello a is a friend of b and c"
// es5 syntax
var result_es5 = arr.reduce(function (str_data, replacement, idx) {
return str_data.replace("{" + (idx + 1) + "}", replacement);
}, str);
console.log(result_es5); // "Hello a is a friend of b and c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment