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

js replace函数用法

作者:不必假装在乎   发布日期:2026-01-12   浏览:22

// 使用 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

大家都在看

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 数组对象合并

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

Laravel 中文站