// 示例代码:使用正则表达式替换字符串中的内容
// 原始字符串
let str = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
// 使用正则表达式替换电子邮件地址为 "[EMAIL]"
let emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
let resultWithEmailReplaced = str.replace(emailRegex, '[EMAIL]');
console.log(resultWithEmailReplaced); // 输出: Hello, my email is [EMAIL] and my phone number is 123-456-7890.
// 使用正则表达式替换电话号码为 "[PHONE]"
let phoneRegex = /\d{3}-\d{3}-\d{4}/g;
let resultWithPhoneReplaced = str.replace(phoneRegex, '[PHONE]');
console.log(resultWithPhoneReplaced); // 输出: Hello, my email is example@example.com and my phone number is [PHONE].
// 同时替换电子邮件和电话号码
let resultWithBothReplaced = str.replace(emailRegex, '[EMAIL]').replace(phoneRegex, '[PHONE]');
console.log(resultWithBothReplaced); // 输出: Hello, my email is [EMAIL] and my phone number is [PHONE].
emailRegex:用于匹配电子邮件地址,模式是 [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,},表示匹配常见的电子邮件格式。phoneRegex:用于匹配电话号码(假设格式为 xxx-xxx-xxxx),模式是 \d{3}-\d{3}-\d{4},表示三个数字、一个连字符、三个数字、一个连字符、四个数字。str.replace() 方法结合正则表达式来替换匹配的内容。例如,将电子邮件地址替换为 [EMAIL],将电话号码替换为 [PHONE]。希望这个示例能帮助你理解如何在 JavaScript 中使用正则表达式进行字符串替换。
上一篇:js replace全部替换
下一篇:js 文本替换
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站