Skip to content

Instantly share code, notes, and snippets.

@kuckmc01
Last active June 19, 2022 02:39
Show Gist options
  • Save kuckmc01/135e6ef04521d1f22bbdeb1901d1cd65 to your computer and use it in GitHub Desktop.
Save kuckmc01/135e6ef04521d1f22bbdeb1901d1cd65 to your computer and use it in GitHub Desktop.
String replacement in javascript for {0}, {2}...{n} values in string
//Using string replace
const x = 'hello {0}, my name is {1}';
const y = ['world','guy'];
const z = x.replace(/\{\d+\}/g, (match) => (y[match.replace(/\{|\}/g,'')]));
console.log(z);
// Using for each
let s = 'hello {0}, my name is {1}';
y.forEach((value,index) => { s = s.replace('{'+index+'}',value)})
console.log(s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment