admin管理员组

文章数量:1401930

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?

Share Improve this question edited Jun 16, 2017 at 4:20 user663031 asked Jun 16, 2017 at 4:00 Yash ThakorYash Thakor 1293 silver badges10 bronze badges 3
  • 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? – user663031 Commented Jun 16, 2017 at 4:05
  • Possible duplicate of How to replace all occurrences of a string in JavaScript? – user663031 Commented Jun 16, 2017 at 4: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 Commented Jun 16, 2017 at 4:22
Add a ment  | 

1 Answer 1

Reset to default 5

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

本文标签: javascriptI want to replace 3939 with 3939Stack Overflow