在JavaScript(.js文件)中,replace()
是一个字符串方法,用于在字符串中查找匹配的子字符串,并将其替换为新的子字符串。这个方法基于提供的可能是字符串或正则表达式的搜索值来执行这个操作。
str.replace(searchValue[, newValue])
searchValue
:必需。要被替换的子字符串或正则表达式。newValue
:可选。用于替换 searchValue
的新字符串。如果省略,则删除 searchValue
。let str = "Hello, world!";
let newStr = str.replace("world", "JavaScript");
console.log(newStr); // 输出 "Hello, JavaScript!"
let str = "I have 3 apples and 5 oranges.";
let newStr = str.replace(/\d+/g, function(match) {
return parseInt(match) * 2;
});
console.log(newStr); // 输出 "I have 6 apples and 10 oranges."
let str = "hello, world!";
let newStr = str.replace(/\b\w+\b/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
});
console.log(newStr); // 输出 "Hello, World!"
replace()
方法不会修改原始字符串,而是返回一个新的字符串。replace()
只会替换第一个匹配的子字符串。要替换所有匹配项,请使用正则表达式并添加全局标志(g
)。领取专属 10元无门槛券
手把手带您无忧上云