// 使用 replace 方法替换字符串中的指定内容
// 示例 1: 替换第一个匹配项
let str = "Hello world!";
let newStr = str.replace("world", "JavaScript");
console.log(newStr); // 输出: Hello JavaScript!
// 解释: replace 方法将字符串中的 "world" 替换为 "JavaScript",只替换第一个匹配项。
// 示例 2: 使用正则表达式进行全局替换
let text = "The rain in SPAIN stays mainly in the plain";
let newText = text.replace(/ain/g, "ain(NEW)");
console.log(newText); // 输出: The rain(NEW) in SPAIN stays mainly(NEW) in the plain
// 解释: 使用正则表达式 /ain/g 进行全局替换,所有匹配 "ain" 的地方都会被替换为 "ain(NEW)"。
// 示例 3: 使用函数作为替换值
let price = "Price is $100";
let result = price.replace(/\$(\d+)/, function(match, p1) {
return "$" + (parseInt(p1) * 0.9); // 打九折
});
console.log(result); // 输出: Price is $90
// 解释: 使用函数作为第二个参数,match 是匹配到的整个字符串,p1 是捕获组 (\d+)。这里我们将价格打九折。
上一篇:js hashmap
下一篇:js class static
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站