I want to replace backslash => '\' with secure \
replacement.
我想用secure \ replacement替换反斜杠=>'\'。
But my code replacing all '#' fails when applied for replacing '\':
但是当我申请替换'\'时,我的代码替换所有'#'失败:
el = el.replace(/\#/g, '#'); // replaces all '#' //that's coolel = el.replace(/\\/g, '\'); // replaces all '\' //that's failing
Why?
2 个解决方案
#1
9
open console and type
打开控制台和类型
'\'.replace(/\\/g, '\');
fails because the slash in the string isn't really in the string, it's escaping '
失败,因为字符串中的斜杠不在字符串中,它正在逃避'
'\\'.replace(/\\/g, '\');
works because it takes one slash and finds it.
有效,因为它需要一个斜杠并找到它。
your regex works.
你的正则表达式工作。
#2
0
You can use String.raw to add slashes conveniently into your string literals. E.g. String.raw`\a\bcd\e`.replace(/\\/g, '\');
您可以使用String.raw方便地将斜杠添加到字符串文字中。例如。 String.raw` \ a \ bcd \ e`.replace(/ \\ / g,'\');
#1
9
open console and type
打开控制台和类型
'\'.replace(/\\/g, '\');
fails because the slash in the string isn't really in the string, it's escaping '
失败,因为字符串中的斜杠不在字符串中,它正在逃避'
'\\'.replace(/\\/g, '\');
works because it takes one slash and finds it.
有效,因为它需要一个斜杠并找到它。
your regex works.
你的正则表达式工作。
#2
0
You can use String.raw to add slashes conveniently into your string literals. E.g. String.raw`\a\bcd\e`.replace(/\\/g, '\');
您可以使用String.raw方便地将斜杠添加到字符串文字中。例如。 String.raw` \ a \ bcd \ e`.replace(/ \\ / g,'\');