Jquery-反斜杠字符
我在尝试替换字符串中的反斜杠字符时遇到问题:
var g = myReadString;
g = g.replace("\", "\\\\");
它给出了无法识别的字符的错误。
一个简单的\
怎么可能被四个\\\\
代替呢?
我将不胜感激任何帮助, 谢谢。 潘迪
I am having a problem trying to replace the backslash character from a string:
var g = myReadString;
g = g.replace("\", "\\\\");
it is giving an error of unrecognized character.
How could a simple \
be replaced with four \\\\
?
I would appreciate any help,
thanks.
Pandy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
\
是转义序列的开始。如果您想按字面意思编写\
,则需要编写\\
,它也是一个转义序列,并将被解释为单个\.因此,如果你想用四个
\\\\
替换一个\
,你需要这样写:但这只会替换第一次出现的单个
\
。要进行全局替换,您需要使用带有全局匹配修饰符的正则表达式:The
\
is the begin of an escape sequence. If you mean to write\
literally, you need to write\\
that is an escape sequence as well and will be interpreted as a single\
. So if you want to replace one\
by four\\\\
, you need to write this:But this will only replace the first occurrence of a single
\
. To do a global replace you need to use a regular expression with the global match modifier:我想这就是你要找的。如果没有请告诉我。
I think that's what you're looking for. Let me know if not.
反斜杠也用作转义字符。您可以在此页面上找到字符列表... http://www.c- point.com/javascript_tutorial/special_characters.htm
因此,为了搜索或替换反斜杠,您必须转义反斜杠。实际上,我刚刚运行了您的代码,但它不起作用,因为反斜杠转义了第一个引号。你到底想做什么?如果你想用双反斜杠替换每个单反斜杠,你将需要这样的东西。
希望有帮助!
The backslash also serves as an escaping character. You can find a list of characters on this page... http://www.c-point.com/javascript_tutorial/special_characters.htm
So, in order to search for, or replace a backslash, you have to escape the backslash. I actually just ran your code, and it doesn't work, as the backslash is escaping the first quote. What exactly are you trying to do? If you want to replace each single backslash with a double, you will need something like this.
Hope that helps!
一般来说,请确保始终正确转义。
在
replace()
的第一个参数中,您打算传递一个包含\
的字符串,但最终结果为",
(quote-comma-space)! 这是因为您实际上转义了字符串上的“结束”引号:
第一个参数是字符串 quote-comma-space。
现在
第一个参数:字符串
\
第二个参数:字符串
\\\\
In general make sure to always escape correctly.
In your first argument for
replace()
you intend to pass a string containing\
but it ends up as",
(quote-comma-space)! This is because you're actually escaping the "closing" quote on the string:
Now the first argument is the string quote-comma-space. The rest gives a syntax error!
What you wanted:
First argument: The string
\
Second argument: The string
\\\\