如何在JavaScript中逃避反斜杠? [英] How to escape backslash in JavaScript?
本文介绍了如何在JavaScript中逃避反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用安全\
替换替换反斜杠=>'\'。
I want to replace backslash => '\' with secure \
replacement.
但是我的代码替换所有'#'在申请替换'\'时失败:
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
为什么?
推荐答案
打开控制台并输入
'\'.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.
你的正则表达式有效。
这篇关于如何在JavaScript中逃避反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文