0

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

var str ='Visit\ Microsoft \'; 

var res = str.replace(/\//g, "-");
alert(res);
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. Commented Feb 22, 2014 at 15:00

5 Answers 5

2

Use:

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

So you need to use backslash (\) instead of forward slash (/).

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

Another approach.

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

Comments

0

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.

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.