// 示例代码:使用 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
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站