Last active
June 19, 2022 02:39
-
-
Save kuckmc01/135e6ef04521d1f22bbdeb1901d1cd65 to your computer and use it in GitHub Desktop.
String replacement in javascript for {0}, {2}...{n} values in string
This file contains 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
//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