View Full Version : Replacing backslashes

07-06-2007, 12:45 PM
Hey, i've hit a bit of a snag while using the replace function. Basically what i need to do is replace all instances of the string: \"
with the string: \\"
The code i'm using at the moment is as follows:

URL = URL.replace("\"", "\\\"")

this works, but only replaces the first instance, and when i try to add the g-flag it stops working. I'm really stumped on this one, any ideas?

Thanks in advance :)

Philip M
07-06-2007, 02:07 PM
URL = 'xxxxx\\"' // backslash must be escaped
alert (URL);
URL = URL.replace(/\\"/,'\\\\"')
alert (URL);

Somewhat wearily, I would like to mention that the gruesome expression "Thanks in advance" so beloved by newcomers is impolite, and takes the assistance given for granted. Most people are taught "Please" before, "Thanks" afterwards.

07-06-2007, 02:26 PM
Hey, thank you for your quick response. I apologise for my comment, i never thought of it that way before and i certainly didn't intend it that way. With regards to the code you posted, it wasn't quite what i meant.
The code you posted replaces the first instance of: \\"
with: \\\"
Also, for the URL i can't add another backslash to: \"
unless there is a function in javascript to do so. I don't think i was that far off the answer, i just need the code i posted to work globally on all instances of the string rather than just the first occurrence.

07-06-2007, 02:31 PM
Just cracked it, cheers for your help though

originalURL = originalURL.replace(/\"/g, '\\\"')

Philip M
07-06-2007, 02:45 PM
Yes, that's it. Sorry I misunderstood what you were trying to do.