0

I want to replace '\' with '/' in JavaScript. I have tried:

link = '\path\path2\';
link.replace("\\","/");

but this isn't working. Am I doing this wrong? If yes what's the correct way?

Yash Thakor
  • 129
  • 3
  • 10
  • You're probably better off using node's built-in ability to use platform-appropriate delimiters in paths. By the way, what is your question? –  Jun 16 '17 at 04:05
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) –  Jun 16 '17 at 04:18
  • How are you storing your string using single backslashes? Your path is going to escape the letter `\p` twice and the closing single quote `\'`. – Soviut Jun 16 '17 at 04:22

1 Answers1

4

string.replace() returns a string. Strings can't be mutated so it doesn't update the string in place.

Return Value

A new string with some or all matches of a pattern replaced by a replacement.

You need to reassign the return value of the replacement to your link variable.

var link = '\path\path2\';
link = link.replace("\\","/");

Additionally, when you use strings as the matching pattern, the replace() function will only replace the first occurrence of the characters you're trying to replace. If you want to replace all occurrences, you need to use regular expressions (regex).

link = link.replace(/\\/g, '/');

the / ... / is a special way of encapsulating a regular expression in Javascript. The \\ is is the escaped backslash. Finally, the g at the end means "global", so the replacement will replace all occurrences of the \ with /. Here is a working example.

var link = '\\path\\path2\\';
link.replace(/\\/g, '/');
console.log(link);
Soviut
  • 88,194
  • 49
  • 192
  • 260
  • Might be important to mention that `replace` only replaces the first occurrence when you give it a string, too. – Ry- Jun 16 '17 at 04:12
  • @Ryan I've updated my answer to include this and an explanation of regex for doing global replacement. – Soviut Jun 16 '17 at 04:17
  • yes that replaces only first occurrence. is their any way to replace all at once. – Yash Thakor Jun 16 '17 at 04:19