function generateStr(str) { const reg = /(\d+)\[(\w+)\]/g; let res = str; while(reg.test(res)){ res = res.replace(reg, (...params) => { // console.log(params) return params[2].repeat(Number(params[1])); }) } return res; }; console.log(generateStr("2[e2[d]]"))