Yash Thakor
Yash Thakor

Reputation: 129

I want to replace '\' with '/'

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?

Upvotes: 0

Views: 9126

Answers (1)

Soviut
Soviut

Reputation: 91685

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);

Update for 2020

Around 2020 String.replaceAll() was introduced which does the same thing as the regular expression above, but using normal string literals.

link = link.replaceAll('\\', '/');
console.log(link);

Upvotes: 5

Related Questions