admin管理员组

文章数量:1406177

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.

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.

Share Improve this question edited Feb 19, 2021 at 22:13 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 24, 2009 at 6:30 xorpowerxorpower 19k52 gold badges131 silver badges185 bronze badges 1
  • Peeve of mind, but please learn... "/" is slash, and "\" is backslash. – Randal Schwartz Commented Dec 24, 2009 at 7:04
Add a ment  | 

3 Answers 3

Reset to default 9

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.

Try this:

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

You need to escape the slash char.

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

A single backslash escapes the following character.

本文标签: aspnetJavascript replace hypen with slashStack Overflow