// 使用 replace 方法
let str = "Hello world, welcome to the world of JavaScript!";
let newStr = str.replace("world", "universe");
console.log(newStr); // 输出: Hello universe, welcome to the universe of JavaScript!
// 解释: replace 只会替换第一个匹配的子字符串,后面的不会被替换。
// 使用 replaceAll 方法
let str2 = "Hello world, welcome to the world of JavaScript!";
let newStr2 = str2.replaceAll("world", "universe");
console.log(newStr2); // 输出: Hello universe, welcome to the universe of universe!
// 解释: replaceAll 会替换所有匹配的子字符串。
上一篇:js replace /g
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站