Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 字符串replace

作者:青灯寂焚   发布日期:2025-10-24   浏览:45

// 示例代码:使用 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

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站