# Special objects
# String object
The String object is used to represent and manipulate a sequence of characters.
As already mentioned in the syntax rules, you can write strings with:
- single quotes:
'string with single quotes'
- double quotes :
"string with double quotes"
- back ticks or template literals:
`string with back ticks`
REMARKS
Strings can be created as primitives (default) or as objects with the new String()
constructor:
const string1 = "A string primitive";
console.log("typeof string1:", typeof string1); // result: typeof string1: string
const string2 = new String("A String object");
console.log("typeof string2:", typeof string2); // result: typeof string2: object
2
3
4
5
This also applies to numbers (new Number()
) and booleans (new Boolean()
)
Internally, JavaScript automatically converts between (string) primitives and (String) objects, which means we can use the (String) object properties and methods on a (string) primitive as well
# Template literals
Template literals use back ticks (` `
) rather than single or double quotes and can hold a variable/expression enclosed within them
With "normal" strings, you have to concatenate strings and variables/expressions with the +
sign
With template literals you can embed variables/expressions inside the back ticks with ${}
(which makes your code more readable)
Line 5 and line 8 give exactly the same result (5 + 7 = 12
)
const a = 5;
const b = 7;
// without template literals
console.log(a + " + " + b + " = " + (a + b));
// with template literals
console.log(`${a} + ${b} = ${a + b}`);
2
3
4
5
6
7
8
# Frequently used properties
property | description |
---|---|
length (opens new window) | the length of a string |
# Frequently used methods
method | description |
---|---|
charAt(<n>) (opens new window) | returns the character at position <n> |
indexOf(<str>) (opens new window) | returns the position of the first occurrence of <str> returns -1 if not found |
lastIndexOf(<str>) (opens new window) | returns the position of the last occurrence of <str> returns -1 if not found |
startsWith(<str>) (opens new window) | returns true if the string begins with <str> , and false if not |
endsWith(<str>) (opens new window) | returns true if the string ends with <str> , and false if not |
includes(<str>) (opens new window) | returns true if the string contains <str> , and false if not |
concat(<str1>, [<str2>]) (opens new window)* | concatenates two (or more) strings |
replace(<pattern>, <str>) (opens new window)* | replaces some or all matches of a <pattern> (string or regex) with <str> |
toLowerCase() (opens new window)* | converts a string to lowercase letters |
toUpperCase() (opens new window)* | converts a string to uppercase letters |
trim() (opens new window)* | removes whitespace from both ends (start and end) of a string |
match(<regex>) (opens new window) | returns an array of strings matching the <regex> or null is there is no match |
split(<pattern>) (opens new window) | splits a string into an array of substrings, based on the <pattern> (string or regex) |
substring(<n1>, [<n2>]) (opens new window) | returns a portion of a string starting at position <n1> and optionally ending at position <n2> |
* These methods return a new string and do not affect the value of the string on which the method is called
# Number object
# Frequently used methods
method | description |
---|---|
toFixed(<digits>) (opens new window) | formats a number as a string using fixed-point notation (with <digits> the number of digits after the decimal point) |
Number.isInteger(<value>) (opens new window) * | returns true if the passed <value> is an integer, and false if not |
parseInt(<str>) (opens new window) ** | converts the numeric string <str> to an integer |
parseFloat(<str>) (opens new window) ** | converts the numeric string <str> to a floating point number |
* This method is a so-called static method and should be preceded by Number.
** These methods are also static methods (and can be called as e.g. Number.parseInt(<str>)
), but they also exist as global functions (and can be called as e.g. parseInt(<str>)
)
TIP
- Instead of using
parseInt()
andparseFloat()
, you can also place a+
sign just before the numeric string -const a = +'5.5'
is the same asconst a = parseFloat('5.5')
-const b = +'7'
is the same asconst b = parseInt('7')
# Math object
The Math
object is a built-in object with mathematical constants (properties) and methods
Unlike many other built-in objects, Math
is a static object which has no constructor, so every property/method starts with Math.
# Frequently used (static) properties
property | description |
---|---|
Math.PI (opens new window) | a constant that approximately equals 3.14159 |
# Frequently used (static) methods
methode | description |
---|---|
Math.ceil(<x>) (opens new window) | round <x> up to the nearest integer |
Math.floor(<x>) (opens new window) | round <x> down to the nearest integer |
Math.round(<x>) (opens new window) | round <x> to the nearest integer (>= .5 round up, < .5 round down) |
Math.random() (opens new window) | generate a random number between 0 (included) and 1 (excluded) |
Math.abs(<x>) (opens new window) | returns the absolute value of <x> |
# Date object
The Date
object is a built-in object for working with dates and times
A Date object must be created through the new Date()
constructor
The date/time is based on the browser settings, so the result depends on the timezone you're in!
# Constructor
There are four ways to instantiate a date:
new Date()
: the current date and timenew Date(year, month, day, hours, minutes, seconds, ms)
: every property aftermonth
is optionalnew Date(ms)
: milliseconds after Jan 1 1970new Date(dateString)
example | result: d = ... |
---|---|
let d = new Date(); |
|
let d = new Date(2020, 0, 31); |
|
let d = new Date(0); |
|
let d = new Date('October 16, 1964 11:13:00'); |
|
REMARK
You need to reload this page to see actual dates in the "result" column of the tables on this page!
# Frequently used methods
# Get or set portions of a date
get | set | description |
---|---|---|
getDay() (opens new window) | get the day of the week from 0 (Sunday) to 6 (Saturday) | |
getDate() (opens new window) | setDate() (opens new window) | get/set the day of the month from 1 to 31 |
getMonth() (opens new window) | setMonth() (opens new window) | get/set the month from 0 (Januari) to 11 (December) |
getFullYear() (opens new window) | setFullYear() (opens new window) | get/set the year |
getHours() (opens new window) | setHours() (opens new window) | get/set the hour from 0 to 23 |
getMinutes() (opens new window) | setMinutes() (opens new window) | get/set the minutes from 0 to 59 |
getSeconds() (opens new window) | setSeconds() (opens new window) | get/set the seconds from 0 to 59 |
getMilliseconds() (opens new window) | setMilliseconds() (opens new window) | get/set the milliseconds from 0 to 999 |
# Convert date to different formats
convert | result |
---|---|
toString() (opens new window) |
|
toLocaleString() (opens new window) | (browser default format and timezone) |
toLocaleString('en-US', { timeZone: 'America/New_York' }) |
|
toUTCString() (opens new window) |
|
toISOString() (opens new window) |
|
toDateString() (opens new window) |
|
toLocaleDateString() (opens new window) | (browser default format and timezone) |
toLocaleDateString('en-US', { timeZone: 'America/New_York' }) |
|
toTimeString() (opens new window) |
|
toLocaleTimeString() (opens new window) | (browser default format and timezone) |
toLocaleTimeString('en-US', { timeZone: 'America/New_York' }) |
|
TIP
It's not always that easy to parse, validate, manipulate and display dates and times in the way you want. There are several JavaScript libraries that can help you with this:
- Moment.js (opens new window): you see this library often in examples, but the project has retired on september 2020
- Luxon (opens new window): the successor of Moment.js but with a different API
- Day.js (opens new window): a fast (2 kB) replacement for Moment.js with the same API as Moment.js