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
1 Answer
Reset to default 5string.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
版权声明:本文标题:javascript - I want to replace '' with '' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744323765a2600630.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论