0

Possible Duplicate:
replace all occurrences in a string

I have this string:

"12-3-02"

And I would like to convert it to :

"12/3/02"

How would I do this? I 've tried :

.replace(/-/,"/")

But this only replaces the first one it finds. How do I replace all instances?

Community
  • 1
  • 1
Trip
  • 26,756
  • 46
  • 158
  • 277

5 Answers5

4

One of these (using split, or a global RegEx flag):

str = str.split('-').join('/'); // No RegExp needed

str = str.replace(/-/g, '/');   // `g` (global) has to be added.
Rob W
  • 341,306
  • 83
  • 791
  • 678
4

Add the g (global) modifier to the regex, to match all -s.

.replace(/-/g,"/")
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

If you want to replace all the occurences of - by / then use this where g specifies the global modifier.

"12-3-02".replace(/-/g,"/");

Working demo - http://jsfiddle.net/ShankarSangoli/QvbM8/

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
3

Try with:

"12-3-02".replace(/-/g, '/');
hsz
  • 148,279
  • 62
  • 259
  • 315
1

This question has been posed about a thousand times, but no one has ever considered the possibility that, in the real world, characters can occur in places where you might not expect.(Typo's in input or replacing parts of words when you only wanted to replace a single word...

var reformat = '01-11-2012'.replace(/(([0-9]+)(?=\-))\-(?=[0-9])/g,'$1/');

This will only replace '-' characters that are preceded and followed by a number.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149