Created
December 5, 2017 06:44
-
-
Save pramodmg/629ded676b1fc634b9242868bbd63973 to your computer and use it in GitHub Desktop.
Replacing an array with an index values of the String
This file contains hidden or 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
// 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