首页 > 解决方案 > 替换字符串中的所有“\/”

问题描述

所以目标在理论上非常简单。我想\/从字符串中替换每个。

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”。

标签: javascript

解决方案


\第一个问题是,您的字符串中没有

第二个问题是您需要使搜索字符串\也包含 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)


推荐阅读