1

how do i format a string of 2014-09-10 10:07:02 into something like this:

2014,09,10,10,07,02

Thanks!

Steven Kwok
  • 199
  • 4
  • 15
  • 1
    Select ["-"," ",":"] and then replace with ",". Should be pretty straightforward. – Travis J Nov 23 '16 at 00:32
  • Please read [my comment](http://stackoverflow.com/questions/40754124/javascript-timestamp-formatting-with-regular-expression/40754211#comment68734344_40754211) on the accepted answer so that you'll better understand what you're using. – canon Nov 23 '16 at 00:53
  • See the addendum to my answer noting that it is imperative to specify the radix if you intend to manipulate these numbers (e.g. using parseInt). – kwah Nov 23 '16 at 02:15

2 Answers2

1

Nice and simple.

var str = "2014-09-10 10:07:02";

var newstr = str.replace(/[ :-]/g, ',');

console.log(newstr);
canon
  • 40,609
  • 10
  • 73
  • 97
Neil Docherty
  • 555
  • 4
  • 20
0

Based on the assumption that you want to get rid of everything but the digits, an alternative is to inverse the regex to exclude everything but digits. This is, in effect, a white-listing approach as compared to the previously posted black-listing approach.

var dateTimeString = "2016-11-23 02:00:00";
var regex = /[^0-9]+/g; // Alternatively (credit zerkms): /\D+/g

var reformattedDateTimeString = dateTimeString.replace(regex, ',');

Note the + which has the effect of replacing groups of characters (e.g. two spaces would be replaced by only a single comma).

Also note that if you intend to use the strings as digits (e.g. via parseInt), numbers with a leading zero are interpreted within JavaScript as being base-8.

Community
  • 1
  • 1
kwah
  • 1,149
  • 1
  • 13
  • 27
  • "numbers with a leading zero are interpreted within JavaScript as being base-8." --- not anymore. – zerkms Nov 23 '16 at 02:15
  • @zerkms While I must admit that this is news to me (thank you for the update!), note that the MDN page I linked to states it is implementation-specific and advises to always specify the radix. – kwah Nov 23 '16 at 02:23
  • It's not implementation specific since ES2015 http://www.ecma-international.org/ecma-262/6.0/#sec-parseint-string-radix (see steps 10-11) – zerkms Nov 23 '16 at 02:25