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

js string replace

作者:半写的温柔ノ   发布日期:2025-03-12   浏览:239

// 示例代码:使用 JavaScript 的 String.replace() 方法

// 简单替换
let str = "Hello, World!";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // 输出: Hello, JavaScript!

// 使用正则表达式进行全局替换
let text = "The rain in SPAIN stays mainly in the plain.";
let newText = text.replace(/ain/g, "ain*");
console.log(newText); // 输出: The rain* in SPAIN* stays mainly* in the plain*.

// 使用函数作为参数进行动态替换
let price = "Price is 100 dollars";
let finalPrice = price.replace(/\d+/g, function(match) {
    return parseInt(match) * 2; // 将匹配到的数字乘以2
});
console.log(finalPrice); // 输出: Price is 200 dollars

解释说明:

  • replace() 方法用于在字符串中搜索指定的子字符串或正则表达式,并用新的子字符串替换匹配的部分。
  • 第一个参数可以是子字符串或正则表达式。如果使用正则表达式,可以通过添加修饰符(如 g 表示全局替换)来控制替换行为。
  • 第二个参数可以是直接替换的字符串,也可以是一个函数,该函数接收匹配的内容作为参数并返回要替换的新值。

上一篇:js replace /g

下一篇:js str_replace

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

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

Laravel 中文站