// 示例代码:使用 replace 方法替换字符串中的内容
// 基本用法:替换第一个匹配项
let str = "Hello world!";
let newStr = str.replace("world", "JavaScript");
console.log(newStr); // 输出: Hello JavaScript!
// 使用正则表达式进行全局替换(所有匹配项)
str = "The rain in SPAIN stays mainly in the plain.";
newStr = str.replace(/ain/g, "ain(NEW)");
console.log(newStr); // 输出: The rain(NEW) in SPAIN stays mainly(NEW) in the plain.
// 使用函数作为参数,动态生成替换内容
str = "1 plus 2 equals 3";
newStr = str.replace(/\d+/g, function(match) {
return parseInt(match) * 2;
});
console.log(newStr); // 输出: 2 plus 4 equals 6
replace 方法用于在字符串中查找指定的值,并用新的值替换它。g),则会替换所有匹配项。上一篇:js 数组倒叙
下一篇:js 字符串转blob
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站