replace() & replaceAll()

replace():取代(首個)…

//方法會傳回一個新字串,此新字串是透過將原字串與 pattern 比對,以 replacement 取代吻合處而生成

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const p
const pReplace=p.replace('dog', 'monkey');
console.log('Preplace',pReplace);
//"The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

replaceAll()取代所有…

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const  pReplaceAll=p.replaceAll('dog', 'monkey');
console.log('PreplaceAll',pReplaceAll);
//"The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
//"The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"