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