最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to remove(backslash ) symbol from string using javascript? - Stack Overflow

programmeradmin1浏览0评论

how to remove \ (backslash ) symbol from string using javascript

var str ='Visit\ Microsoft \'; 

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

how to remove \ (backslash ) symbol from string using javascript

var str ='Visit\ Microsoft \'; 

var res = str.replace(/\//g, "-");
alert(res);
Share Improve this question edited Mar 3, 2014 at 11:50 Rajiv Pingale 1,01510 silver badges27 bronze badges asked Feb 22, 2014 at 14:58 user3319802user3319802 591 silver badge7 bronze badges 1
  • 1 As posted, your JavaScript string will not have any backslash characters in it (and it's a backslash, not a "slash"). If it did, you'd need to use the regex /\\/g to find them. – Pointy Commented Feb 22, 2014 at 15:00
Add a ment  | 

5 Answers 5

Reset to default 2

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

Demo: Fiddle

Another approach.

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

Have you noticed the color change in your HTML Code?

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.

\ 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.

var str ='Visit\ Microsoft \'; will not work, coz its invalid..

var str ='Visit\\ Microsoft \\'; -- is the correct js string

发布评论

评论列表(0)

  1. 暂无评论