replace
方法用于替换字符串中指定模式的文本部分。它可以用来查找一个字符串中的特定文本,然后将其替换为新的文本,生成一个新的字符串。replace
方法并不会修改原始字符串,而是返回一个包含替换结果的新字符串。
string.replace(searchValue, newValue);
参数
replace
方法会查找原始字符串中的第一个匹配项,并将其替换为新的字符串。如果 searchValue 是正则表达式并具有全局标志 (g),则它会替换所有匹配项,否则只替换第一个匹配项。
let str = "Hello, world!";
let newStr = str.replace("world", "universe");
console.log(newStr); // 输出: "Hello, universe!"
let str2 = "I love cats, cats are great!";
let newStr2 = str2.replace(/cats/g, "dogs");
console.log(newStr2); // 输出: "I love dogs. dogs are great!"