String#replace 可以将函数作为其第二个参数,因此您可以基于某些逻辑提供替换。
"Some string Some".replace(/Some/g, (match, startIndex, wholeString) => { if(startIndex == 0){ return 'Start'; } else { return 'End'; } }); // 将返回Start字符串End
一线模板库
let data = {name: 'John', surname: 'Doe'} "My name is {surname}, {name} {surname}".replace(/(?:{(.+?)})/g, x => data[x.slice(1,-1)]); // "My name is Doe, John Doe"