Console Learner — An interactive JavaScript course.


4.9 Date & RegExp Objects

>>>
new Date()
Thu Apr 06 2023 13:43:30 GMT+0200 (Central European Summer Time)
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 milliseconds elapsed since Jan 01 1970 00:00:00 UTC (also known as Unix epoch).
>>>
new Date().getTime()
1680781410400
The Date.prototype.getTime() method (or Date.now() since ES5) can be used to access the current time (in milliseconds).
>>>
+(new Date(987654321000))
987654321000
It is also possible to coerce a Date object into a number to get the milliseconds elapsed.
>>>
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')
["foo"]
>>>
re.exec('foo bar')
["bar"]
A RegExp object instance contains both a compiled regular expression and the current matcher state (in the lastIndex property). This allows repeated calls to exec() to find repeated matches (e.g. in a loop).
>>>
re.exec('xyz')
null
This can have unintended consequences if the matching string is changed without also setting lastIndex to zero.
>>>
'foo bar baz'.match(re)
["foo", "bar", "baz"]
Use the String.prototype.match() or String.prototype.matchAll() methods instead to avoid issues.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.