javascript - 替换字符串中的所有“\/”
问题描述
所以目标在理论上非常简单。我想\/
从字符串中替换每个。
const a = '/\/awd\//g'.replaceAll('\\/', '');
const b = '/\/awd\//g'.replace(/\\\//g, '');
const c = '/\/awd\//g'.replace('/\\/g', '');
const d = '/\/awd\//g'.replace('/\\//', '');
console.log(a, b, c, d);
结果应该是:/awd/g
;
有没有办法做到这一点?我不想使用地图或遍历每个字母。我只想将替换函数与正则表达式或子字符串一起使用。\/
而且我不知道字符串里面有多少。谢谢
也可以有“i”或“g”或“m”或“igm”或“ig”或“im”或“mi”等等,而不是最后的“g”。
解决方案
\
第一个问题是,您的字符串中没有
第二个问题是您需要使搜索字符串\
也包含 a
第三个问题是,您尝试使用正则表达式,但改用字符串
所以..要首先在其中创建一个字符串\/
,您必须使用\\/
那么你需要使用"\\/"
它来搜索它,并使用replaceAll来替换它们
或者,使用正则表达式,您需要同时转义 \ 和 / ...并且不使用正则表达式的字符串 - 即搜索应该是
/\\\//g
/ begin regular expression
\ escape the next character
\ literal \
\ escape the next character
/ literal /
/ end regex expression
g global flag
这将取代所有\/
你当然也可以使用“new RegExp(str, flags)”
new Regex('\\\\/', 'g');
我会让你弄清楚为什么里面有 4 \ !
const a = '/\/awd\//g';
const b = '/\\/awd\\//g';
const c = b.replace(/\\\//g, '');
const d = b.replaceAll('\\/', '');
const e = b.replaceAll(new RegExp('\\\\/', 'g'), '');
console.log(a.includes('\\'));
console.log(b.includes('\\'));
console.log(a.split('').join(' '));
console.log(b.split('').join(' '));
console.log(c)
console.log(d)
console.log(e)
推荐阅读
- c# - 使用 NEST 使用 ElasticSearch 2.x 搜索多种类型时,如何获得混合结果?
- mysql - 如何检查 INSERT INTO SELECT 块中一列的两个不同条件?
- javascript - 筛选多个类别的产品
- jfreechart - 在 JFreeChart 中连接设计信封点
- awk - GAWK 使用 -i inplace 选项将字符串打印到 STDOUT
- workflow - 如何将 Watson Knowledge Catalog (WKC) 连接到我的 Oracle Cloud ATP 数据库?
- python - 删除了 jupyter 笔记本单元格 - 有没有办法从仍在内存中的对象返回代码?
- angular - 使用 Angular 自定义电子邮件验证
- shell - 在活动窗口中的选定字段中填充文本 - VBScript、WScript.Shell
- python - 使用 Pandas 根据另一列的值选择一列