用回撥函式替換字串匹配
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"