1. 简单的字符串替换
替换第一次出现的子字符串。
let str = "hello world!";
let result = str.replace("world", "javascript");
// output: "hello javascript!"
2. 全局字符串替换
替换所有出现的子字符串,使用带有正则表达式的全局 (g) 标志。
let str = "hello world, world!";
let result = str.replace(/world/g, "javascript");
// output: "hello javascript, javascript!"
3. 不区分大小写的替换
您可以使用 i 标志使替换不区分大小写。
let str = "hello world, world!";
let result = str.replace(/world/gi, "javascript")
// output: "hello javascript, javascript!"
4.替换整个单词(单词边界)
使用 b 单词边界仅替换整个单词。
let str = "this is a test word, test.";
let result = str.replace(/btestb/, "success");
// output: "this is a success word, test."
替换所有出现的整个单词,使用全局标志。
let str = "this is a test word, test.";
let result = str.replace(/btestb/g, "success");
// output: "this is a success word, success."
5. 使用函数进行替换
您可以将一个函数传递给replace(),以动态生成替换字符串。
let str = "the price is $10";
let result = str.replace(/$d+/g, (match) => {
return `$${parseint(match.substring(1)) * 2}`
});
// output: "the price is $20"
6. 通过替换捕获组
使用正则表达式,您可以捕获匹配的部分内容并在替换字符串中重用它们。
let str = "john smith";
let result = str.replace(/(w+)s(w+)/, "$2, $1");
// output: "smith, john"
7. 转义特殊字符
如果您需要替换特殊字符,例如 .或*,您需要在正则表达式中转义它们。
let str = "price: 5.99";
let result = str.replace(/./, ",");
// output: "price: 5,99"
8. 替换非 ascii 字符
要替换不在 ascii 范围内的字符,您可以使用 unicode 属性。
let str = "héllo wörld";
let result = str.replace(/[^x00-x7f]/g, "");
// output: "hllo wrld"
9. 替换数字
您可以使用正则表达式替换数字(或数字组)。
let str = "contact: 123-456-7890";
let result = str.replace(/d{3}/g, "***");
// output: "contact: ***-***-***0"
10. 使用 unicode 替换特殊字符
您还可以使用 unicode 转义序列来替换特殊字符。
let str = "I love ☕!";
let result = str.replace(/u2615/g, "coffee");
// Output: "I love coffee!"