JavaScript 的 replace() 預設只會替換第一個符合的字串。若想一次取代全部相同內容,需要使用正則表達式並加上 g 旗標。
replace()
g
例如:
str.replace(/a/g, "A")
這樣就能把字串中所有的 a 都替換成大寫 A。若只需要替換第一次出現,則可使用 str.replace("a", "A") 或 str.replace(/a/, "A")。
str.replace("a", "A")
str.replace(/a/, "A")