-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,765
  • 10
  • 83
  • 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
  • 372,613
  • 87
  • 782
  • 758
3

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

/\//g
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 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
  • 447
  • 3
  • 13