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
5 Answers
Reset to default 2Use:
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