在JavaScript中,replace()
方法默認在當前字符串中查找匹配項,并將其替換為新值。它不會自動影響全局范圍,即它只會替換當前字符串中找到的第一個匹配項。
要在全局范圍內(nèi)使用 replace()
方法,您需要使用正則表達式,并在其標志中設置 g
(表示全局搜索)。例如:
let str = "apple, apple pie, apple juice";
let regex = /apple/g;
let newStr = str.replace(regex, "orange");
console.log(newStr); // 輸出 "orange, orange pie, orange juice"
在這個例子中,我們使用正則表達式 /apple/g
來匹配所有包含 “apple” 的子字符串,并將它們替換為 “orange”。這將影響整個字符串,而不僅僅是第一個匹配項。