温馨提示×

JS replace能作用于全局范围吗

js
小樊
81
2024-10-12 11:01:02
栏目: 编程语言

在JavaScript中,replace() 方法默认在当前字符串中查找匹配项,并将其替换为新值。它不会自动影响全局范围,即它只会替换当前字符串中找到的第一个匹配项。

要在全局范围内使用 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”。这将影响整个字符串,而不仅仅是第一个匹配项。

0