views:

154

answers:

3

hi,

how to replace a hypen (-) with a slash (\) in javascript?

for example, i need to replace

C-MyDocuments-VisualStudio2008-MyProjects

with

C\MyDocuments\VisualStudio2008\MyProjects

i tried replace function such as variable.replace("-","\") but it showed me error of unterminated string constant

i am working in VS 2008

Thanks

+3  A: 

You need to escape the slash with an additional backslash like this:

variable = variable.replace("-","\\");

To replace the hyphen globally, try this:

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

This uses a regular expression to search the string for the hyphen and the g modifier indicates that replacements should be global.

Andrew Hare
@@seth, @@Sarfraz, @@Andrew: I tried your solutions but it didn't worked..:-(
Romil Nagrani
@@ Andrew:is any for loop like needed in JS to replace each hyphen, it replaced only first hyphen?
Romil Nagrani
Good point about global replacement - I have added a solution for that as well :)
Andrew Hare
hey this worked!
Romil Nagrani
A: 

Try this:

variable.replace("-","\\")

You need to escape the slash char.

Sarfraz
A: 

Try replacing with "\\" (two backslashes).

A single backslash escapes the following character.

Seth