开发者

Jquery- backslash character

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


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:

g.replace("\\", "\\\\\\\\")

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:

g.replace(/\\/g, "\\\\\\\\")


g = g.replace(/\\/g, "\\\\");

I think that's what you're looking for. Let me know if not.


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.

var g = myReadString;
g = g.replace("\\", "\\\\");

Hope that helps!


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:

g = g.replace("\", "\\\\");
              ^    ^
              s    e
              t    n
              a    d
              r
              t

Now the first argument is the string quote-comma-space. The rest gives a syntax error!

What you wanted:

g = g.replace("\\", "\\\\\\\\");
              ^  ^  ^        ^
              s  e  s        e
              t  n  t        n
              a  d  a        d
              r     r
              t     t

First argument: The string \
Second argument: The string \\\\

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜