
replace() 會找出符合正則表達式或指定字串的內容,並替換成新的子字串。若要全域替換,可使用 g 標記;若要忽略大小寫,可加上 i 標記。
string.replace(regexp, newSubStr)
string.replace(substr, newSubStr)
const re = /apples/gi;
const str = 'Apples are round, and apples are juicy.';
console.log(str.replace(re, 'oranges'));
const re = /(w+)s(w+)/;
const str = 'zara ali';
console.log(str.replace(re, '$2, $1'));
這個範例會把两个單字前後調換,輸出為「ali, zara」。replace() 也可傳入函式,讓替換內容依比對結果動態產生。