1

Let's say I have this string

"examples\output\$projectname$\$projectname$.csproj"

I want to replace all occurences of $projectname$ with some string. E.g. replacing it with TEST should yield:

"examples\output\TEST\TEST.csproj"

The closest I've come to achieving this is:

("examples\output\$projectname$\$projectname$.csproj")
    .replace(new RegExp("\\$projectname\\$", "g"), "TEST");

which yields:

"examplesoutputTESTTEST.csproj"

Even when writing...

("examples\output\$projectname$\$projectname$.csproj")
    .replace(new RegExp("output", "g"), "TEST");

...this will still remove the backslashes

"examplesTEST$projectname$$projectname$.csproj"

Why is this happening and how do I prevent this?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
mode777
  • 3,037
  • 2
  • 23
  • 34
  • 1
    I may be wrong, but I think you need to put an escape character (`/`) in front of your backslashes. – R. McManaman May 23 '17 at 21:40
  • 1
    It's not the regex, it's just your initial string is wrong. [read](https://stackoverflow.com/questions/3903488/javascript-backslash-in-variables-is-causing-an-error) – James May 23 '17 at 21:42

2 Answers2

2

The backslashes aren't even there in the first place:

// Prints "examplesoutput$projectname$$projectname$.csproj":
console.log("examples\output\$projectname$\$projectname$.csproj");

You need to escape the backslashes in your given string literal. A string literal "\$" will evaluate to "$". But a string literal "\\$" will evaluate to "\$":

var path = "examples\\output\\$projectname$\\$projectname$.csproj".replace(new RegExp("\\$projectname\\$", "g"), "TEST");

console.log(path); // "examples\output\TEST\TEST.csproj"
le_m
  • 19,302
  • 9
  • 64
  • 74
  • Thanks a lot. My first solution (just as yours) does indeed work in code where the path is in a variable. I was just forgetting to escape the backslash in the string literal for my testing setup. – mode777 May 23 '17 at 21:49
2

In JavaScript (as with many other languages), the back-slashes in your literal string are acting as escape characters, preserving the character after them; the effect is that the slashes disappear. This means that your string written as:

"examples\output\$projectname$\$projectname$.csproj"

is interpreted as,

"examplesoutput$projectname$$projectname$.csproj"

You would need to use the back-slash to escape the back-slash:

"examples\\output\\$projectname$\\$projectname$.csproj"

Note that if you have a string with single back-slashes in them (from an API which returns Windows file paths, for example), the back-slashes are already part of the string, so it does not need to be processed to escape the existing slashes.

Back to your original code, you needn't create a new RegExp object. Javascript supports regex-literals. So you can write:

"examples\\output\\$projectname$\\$projectname$.csproj"
.replace(/\$projectname\$/g, "TEST")
bill.lee
  • 2,207
  • 1
  • 20
  • 26