// 使用正则表达式替换字符串中的内容
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."
str.replace(/\s/g, '_')
:使用正则表达式 \s
匹配所有空格,并用下划线 _
替换,g
表示全局替换。str.replace(/example/, 'test')
:替换第一个出现的 example
为 test
。str.replace(/example/g, 'test')
:使用正则表达式的 g
标志进行全局替换,将所有的 example
替换为 test
。str.replace(/\d{3}-\d{3}-\d{4}/, 'XXX-XXX-XXXX')
:匹配电话号码格式(三位数-三位数-四位数),并将其替换为 XXX-XXX-XXXX
。上一篇:js 日期计算
下一篇:js tojson
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站