用回调函数替换字符串匹配
String#replace
可以将函数作为其第二个参数,因此你可以根据某些逻辑提供替换。
"Some string Some".replace(/Some/g, (match, startIndex, wholeString) => {
if(startIndex == 0){
return 'Start';
} else {
return 'End';
}
});
// will return Start string 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"