我想用安全\
替换替换反斜杠 => '\' 。
但是当我申请替换“\”时,我的代码替换所有“#”失败:
el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = el.replace(/\\/g, '\'); // replaces all '\' //that's failing
为什么?
我想用安全\
替换替换反斜杠 => '\' 。
但是当我申请替换“\”时,我的代码替换所有“#”失败:
el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = el.replace(/\\/g, '\'); // replaces all '\' //that's failing
为什么?
打开控制台并输入
'\'.replace(/\\/g, '\');
失败,因为字符串中的斜杠实际上不在字符串中,它正在转义 '
'\\'.replace(/\\/g, '\');
有效,因为它需要一个斜线并找到它。
你的正则表达式有效。
您可以使用String.raw方便地将斜杠添加到您的字符串文字中。例如String.raw`\a\bcd\e`.replace(/\\/g, '\');