I want to replace '\' with '/'

前端 未结 1 849
你的背包
你的背包 2021-01-29 07:47

I want to replace \'\\\' with \'/\' in JavaScript. I have tried:

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

but this isn\'t work

相关标签:
1条回答
  • 2021-01-29 08:26

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

    0 讨论(0)
提交回复
热议问题