-2

I need to replace occurrence of very \ with - in a string. I am using the following code but it replace only for once occruence:

var start = '1/1/12';
startNew = start.replace('/', "-"); 

Result i am getting is: 1-1/12

Result i want is: 1-1-12

VMAtm
  • 27,943
  • 17
  • 79
  • 125
user1871640
  • 441
  • 2
  • 8
  • 18

4 Answers4

2

You need to use reqular expression with replace() and need to escape your forward slash.

Live Demo

var start = '1/1/12';
startNew = start.replace(/\//g, "-");

/yourtext/g is syntax for regex for replacing all occurances in replace function, since your text is forward slash / you have to escape it by putting back \ slash befor it.

Adil
  • 146,340
  • 25
  • 209
  • 204
0
startNew = start.replace(/\\//g, "-"); 
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
closure
  • 7,412
  • 1
  • 23
  • 23
0

The following would do but only will replace one occurence:

"string".replace('/', '-'); // same as you have done

For a global replacement, or if you prefer regular expressions, you just have to escape the slash:

"string".replace(/\//g, '-');
Anujith
  • 9,370
  • 6
  • 33
  • 48
0

try this:

start.replace(/\\/g,"-");
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110