javascript interactive

JavaScript Interactive — a console crash course


4.8 Date & RegExp Objects

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
new Date()
Mon Feb 18 2013 17:16:23 GMT+0100 (CET)
The built-in Date constructor creates a new date object initialized to the current date and time. The Date.prototype.toString() method returns a string formatted according to the local timezone.
>>>
new Date(0).toUTCString()
Thu, 01 Jan 1970 00:00:00 GMT
The Date objects are wrappers around the number of seconds elapsed since Jan 01 1970 00:00:00 UTC (also known as Unix time).
>>>
new Date().getTime()
1361204246671
The Date.prototype.getTime() method is commonly used to access the system time (in seconds).
>>>
Date.now()
1361204246671
Modern browsers also support Date.now() as a short-hand and more efficient way of achieving the same result (without creating a wrapper object). See the Mozilla JavaScript Reference for more info.
>>>
new RegExp('[a-z]+', 'g')
/[a-z]+/g
The RegExp function is another built-in constructor that should mostly be avoided, in favor of using the shorter literal syntax.
>>>
var re = /[a-z]+/g;

  
>>>
re.exec('foo bar baz')
["foo"]
The RegExp object instances contain a compiled version of the regular expression.
>>>
re.exec('foo bar baz')
["bar"]
But RegExp objects also maintain a matcher state, with the lastIndex property. This allows repeated calls to exec() for find all matches (e.g. in a loop).
>>>
re.exec('abc123')
null
This can have unintended consequences if the matching string is replaced without also resetting lastIndex to zero.
>>>

Index 1 2 3 4 5 6 7 8