简体   繁体   English

如何使用JavaScript从字符串中删除\\(反斜杠)符号?

[英]how to remove \ (backslash ) symbol from string using javascript?

how to remove \\ (backslash ) symbol from string using javascript 如何使用JavaScript从字符串中删除\\(反斜杠)符号

var str ='Visit\ Microsoft \'; 

var res = str.replace(/\//g, "-");
alert(res);

Use: 采用:

str.replace(/\\/g, "-");

So you need to use backslash ( \\ ) instead of forward slash ( / ). 因此,您需要使用反斜杠( \\ )而不是正斜杠( / )。

it should be 它应该是

var str = 'Visit\\ Microsoft \\';

var res = str.replace(/\\/g, "-");
alert(res);

you need to escape the \\ with another \\ as back slash is a escape character, also the regex should be /\\\\/g 您需要使用另一个\\来转义\\ ,因为反斜杠是转义字符,并且正则表达式也应为/\\\\/g

Demo: Fiddle 演示: 小提琴

另一种方法。

str = str.split('\\').join('').trim()

var str ='Visit\\ Microsoft \\'; var str ='Visit \\ Microsoft \\'; will not work, coz its invalid.. 将不起作用,因为它无效。

var str ='Visit\\\\ Microsoft \\\\'; var str ='Visit \\\\ Microsoft \\\\'; -- is the correct js string -是正确的js字符串

Have you noticed the color change in your HTML Code? 您是否注意到HTML代码中的颜色变化?

var str ='Visit\ Microsoft \'; 

var res = str.replace(/\//g, "-");
alert(res);

Everything after Microsoft is red, that indicates everything after Microsoft is also a string. Microsoft之后的所有内容均为红色,表示Microsoft之后的所有内容均为字符串。

\\ Backslash works as a except character , So it except closing " ' " mark. \\反斜杠用作除字符之外的字符 ,因此除关闭“ ' ”标记外。

Please check your code, you may need to add backslash before Space, like below 请检查您的代码,您可能需要在空格之前添加反斜杠,如下所示

var str ='Visit\ Microsoft\ '; 

var res = str.replace(/\//g, "-");
alert(res);

This Code will work as you wanted. 该代码将按您希望的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM