function replaceDogWithCat(text: string): string {
// 使用正则表达式,i表示不区分大小写,\b表示单词边界
const regex = /\bdog\b/i;
return text.replace(regex, 'cat');
}
// 测试
let text = 'The quick brown fox jumps over the lazy dog. The dog sleeps all day.';
console.log(replaceDogWithCat(text));
代码逻辑解释
- 正则表达式部分:
/\bdog\b/i
这是一个正则表达式。\b
表示单词边界,确保我们匹配的 dog
是一个完整的单词,而不是其他单词的一部分,比如 doghouse
中的 dog
就不会被匹配。i
是修饰符,表示不区分大小写,这样无论 Dog
、DOG
还是 dog
都会被匹配。
replace
方法部分:
text.replace(regex, 'cat')
这里使用了 string
类型的 replace
方法,它会在 text
字符串中查找与正则表达式 regex
匹配的部分,并将其替换为 'cat'
。最终返回替换后的新字符串。