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

js replace 正则

作者:﹏〃对不起╮他是为你哭了   发布日期:2025-09-17   浏览:87

// 使用正则表达式替换字符串中的内容

let str = "Hello, my email is example@example.com and my phone number is 123-456-7890.";

// 替换所有的空格为下划线
let result1 = str.replace(/\s/g, '_');
console.log(result1); // 输出: "Hello,_my_email_is_example@example.com_and_my_phone_number_is_123-456-7890."

// 替换第一个出现的 "example" 为 "test"
let result2 = str.replace(/example/, 'test');
console.log(result2); // 输出: "Hello, my email is test@example.com and my phone number is 123-456-7890."

// 使用正则表达式全局替换所有的 "example" 为 "test"
let result3 = str.replace(/example/g, 'test');
console.log(result3); // 输出: "Hello, my email is test@test.com and my phone number is 123-456-7890."

// 使用正则表达式替换电话号码格式
let result4 = str.replace(/\d{3}-\d{3}-\d{4}/, 'XXX-XXX-XXXX');
console.log(result4); // 输出: "Hello, my email is example@example.com and my phone number is XXX-XXX-XXXX."

解释说明:

  1. str.replace(/\s/g, '_'):使用正则表达式 \s 匹配所有空格,并用下划线 _ 替换,g 表示全局替换。
  2. str.replace(/example/, 'test'):替换第一个出现的 exampletest
  3. str.replace(/example/g, 'test'):使用正则表达式的 g 标志进行全局替换,将所有的 example 替换为 test
  4. str.replace(/\d{3}-\d{3}-\d{4}/, 'XXX-XXX-XXXX'):匹配电话号码格式(三位数-三位数-四位数),并将其替换为 XXX-XXX-XXXX

上一篇:js 日期计算

下一篇:js tojson

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站