I want to replace backslash => '\' with secure \
replacement.
我想用secure \替换反斜杠=> '\';更换。
But my code replacing all '#' fails when applied for replacing '\':
但是我的代码替换了所有的“#”失败,当申请替换“\”:
el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = 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, '\');
您可以使用字符串。raw格式可以方便地将斜线添加到字符串文字中。例如String.raw \ \ bcd \ e。替换(/ \ \ / g,' & # 92;');
#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, '\');
您可以使用字符串。raw格式可以方便地将斜线添加到字符串文字中。例如String.raw \ \ bcd \ e。替换(/ \ \ / g,' & # 92;');