// 使用 replace 方法替换字符串中的内容
let str = "Hello, world!";
let newStr = str.replace("world", "JavaScript");
console.log(newStr); // 输出: Hello, JavaScript!
// 解释说明:
// replace() 方法用于在字符串中搜索指定的子字符串,并用新的子字符串替换它。
// 在上面的例子中,我们将 "world" 替换为 "JavaScript"。
如果需要更复杂的替换(例如使用正则表达式进行全局替换),可以这样做:
let str = "The rain in SPAIN stays mainly in the plain.";
let newStr = str.replace(/ain/g, "ain(NEW)");
console.log(newStr);
// 输出: The rain(NEW) in SPAIN(NEW) stays mainly(NEW) in the plain.
// 解释说明:
// 这里我们使用了正则表达式 /ain/g 来匹配所有出现的 "ain" 并替换成 "ain(NEW)"。
// 'g' 表示全局替换,即替换所有匹配项,而不仅仅是第一个。
上一篇:javascript学习
下一篇:javascript class
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站