我想将'\'替换为'/' [英] I want to replace '\' with '/'

查看:73
本文介绍了我想将'\'替换为'/'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中将'\'替换为'/'. 我已经尝试过:

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() 返回一个字符串.字符串无法突变,因此不会更新字符串.

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

返回值

一个新字符串,其中部分或全部模式匹配项被替换项替换.

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

您需要将替换的返回值重新分配给您的link变量.

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

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

此外,当您使用字符串作为匹配模式时,replace()函数将仅替换您尝试替换的字符的第一个匹配项.如果要替换所有出现的内容,则需要使用正则表达式(regex).

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, '/');

/ ... /是在Javascript中封装正则表达式的一种特殊方法. \\是转义的反斜杠.最后,最后的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);

这篇关于我想将'\'替换为'/'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆