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

JavaScript如何对包含正斜杠的字符串执行不区分大小写的替换

解决方案

在JavaScript的正则字面量中,/是正则的边界标识符,所以如果要匹配正斜杠本身,只需要在正斜杠前加反斜杠\做转义即可,保留gi修饰符就能实现全局不区分大小写的替换。

示例代码

const str = 'http://example.com/lorem/ipsum.txt';
// 正则内部的 / 需用 \ 转义
const replacedStr = str.replace(/\/lorem\//gi, '/ipsum/');
// 输出结果:http://example.com/ipsum/ipsum.txt
console.log(replacedStr);

动态匹配场景写法

如果你的匹配规则是动态生成的,更推荐使用RegExp构造函数创建正则,不需要手动转义正斜杠:

const str = 'http://example.com/lorem/ipsum.txt';
const matchText = '/lorem/';
const replaceText = '/ipsum/';
// 构造函数第二个参数传入修饰符 gi
const reg = new RegExp(matchText, 'gi');
const replacedStr = str.replace(reg, replaceText);

注意:如果使用RegExp构造函数,且匹配文本中包含.、*、?等正则特殊字符时,需要先对这些特殊字符做转义处理,避免正则匹配逻辑不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:36:03