You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现为字符串中所有大小写不敏感的指定单词添加前后缀

JavaScript实现大小写不敏感匹配并包裹目标单词

需求说明

需要对文本中所有大小写形式的单词this进行匹配,在每个匹配结果前加前缀Foo,后加后缀Bar,保留原单词的大小写形式。

示例输入文本:
Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.
预期输出结果:
Hello FooThisBar is a test string FoothisBar is a test FooTHISBar is just a test ok? Can we solve FooThisBar? Idk, maybe FoothiSBar, is just impossible.

实现代码

// 原始文本
const rawText = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.";
// 全局替换
const result = rawText.replace(/this/gi, 'Foo$&Bar');
console.log(result);

规则说明

  • 正则 /this/gi 中的i标识开启大小写不敏感匹配,所有大小写组合的this都可以被命中;g标识开启全局匹配,替换所有命中内容而非仅第一个。
  • 替换字符串中的$&是JS字符串替换的特殊占位符,代表本次匹配到的原始内容,可直接保留原单词的大小写形式,无需额外写回调处理。

内容的提问来源于stack exchange,提问作者Pedram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:27:05