-4

I am trying to change the format of a date in a string from mm/dd/yyyy to mm-dd-yyyy.

I have tried using the following but it does not work

str.replace(///g,"-");
Manse
  • 37,343
  • 10
  • 82
  • 108
Pranay
  • 93
  • 1
  • 1
  • 5

3 Answers3

3

Two problems :

  • you need to escape the / in the regex
  • replace returns a new string and doesn't change the old one (strings are immutable)

Use

str = str.replace(/\//g, "-")
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726
3

Since / delimits the regular expression, if you want to use a / character as data within one, you must escape it:

/\//g
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
  • But this '//' ends up commenting all the thing following g.. – Pranay Jun 07 '13 at 11:02
  • @user2130674 — No, it doesn't. It might look that way if you have a syntax highlighter that doesn't understand JavaScript properly. – Quentin Jun 07 '13 at 11:03
0

it works.

'12/5/13'.replace(/\//g, '-');
Tukuna
  • 437
  • 3
  • 13