A WeakMap object in JavaScript is a collection of key-value pairs where the keys are weakly referenced. The WeakMap keys must be objects or non-registered symbols, and values are of any arbitrary JavaScript type.
The WeakMap is similar to the JavaScript Map. The main difference between the WeakMap and Map data structure is that the WeakMap data structure uses the objects as a key only, but Map can use other data types also as a key.
If you use the value of another data type as a key of a WeakMap except the object, it gives the Types error.
Syntax
You can follow the syntax below to use the WeakMap in JavaScript −
const weak_map =newWeakMap();
In the above syntax, we used the ‘new’ keyword with a WeakMap() function to create a new instance of the WeakMap.
The WeakMap provides methods to set, get, and delete the key-value pairs from the WeakMap. Here, we have listed the properties and methods of the WeakMap.
WeakMap Properties
Here is a list of the properties of WeakMap and their description −
Sr.No.
Name & Description
1
constructorTo get a constructor function of a WeakMap.
WeakMap Methods
Here is a list of the methods associated with WeakMap object and their description −
Sr.No.
Name & Description
1
delete()To delete a single key-value pair from the WeakMap.
2
get()To get values related to the specific object.
3
has()Check whether a particular object exists as a key exists in the WeakMap.
4
set()To insert the key-value pair in the WeakMap.
WeakMap Constructor()
Following is the WeakMap constructor in JavaScript −
In the example below, we have defined the WeakMap using the constructor function. After that, we used the set() method to set the laptop object as a key and its price as a value.
At last, we used the get() method to get the value related to the ‘laptop’ key.
<html><body><p id ="output">The laptop price is:</p><script>const wm =newWeakMap();const laptop ={
If we execute the program, it returns the value related to the "laptop" key, i.e. "10000".
Example: Deleting key-value pair from the WeakMap
In the example below, we have inserted the key-value pair in the WeakMap using the set() method.
After that, we used the delete() method to delete the key-value pair from the WeakMap. After deleting the key-value pair when you access it, the WeakMap returns undefined, as you can see in the output.
Note − WeakMaps are not iterable in JavaScript.
<html><body><div id ="output1">The laptop price is:</div><div id ="output2">The laptop price after deletion is:</div><script>const wm =newWeakMap();const laptop ={
A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs.
To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method.
Syntax
Following is the syntax to use the Map data structure in JavaScript −
const map =newMap([iterable]);
In the above syntax, we used the ‘new’ keyword with a Map() constructor to define an instance of the Map.
Parameters
iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter.
The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map.
Map Properties
Following are the properties of Map object −
Sr.No.
Name & Description
1
sizeThis property returns the number of elements in this map.
Map Methods
In the following table, we have listed all the methods of Map object and their description −
Sr.No.
Name & Description
1
clear()This method removes all elements from a Map object.
2
delete()This method removes a specified element from a Map object by key.
3
entries()This method returns a new map iterator object that contains the [key, value] pairs.
4
forEach()This method executes a callback function once per each key/value pair in a Map object.
5
get()This method is used to return a specified element from a Map object.
6
has()This method indicates whether an element with the specified key exists or not.
7
keys()This method returns a new Iterator object that contains the keys for each element in the Map object.
8
set()This method insert the key-value pair to a Map object.
9
values()This method returns a new Iterator object that containing values of the Map object.
JavaScript Map Constructor()
Following is the constructor of Map in JavaScript −
In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor.
After that, we traverse the map to get each value of the map and show in the output.
<html><body><div> Map elements are:</div><div id ="output"></div><script>const map =newMap([["Apple",100],["Banana",20],["Orange",50]]);for(let[key, value]of map){
After executing the above program, it returns each value of the map.
Map elements are:
Apple : 100
Banana : 20
Orange : 50
Example: Inserting key-value pair in the Map
In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument.
<html><body><div>After inserting 2 key-value pairs in the map:</div><div id ="output"></div><script>const map =newMap();
After executing, it returns all the elements present in the Map object.
Name: John
Roll Id: 123
Example: Removing a Map Element
In the example below, we use the delete() method to delete the key-value pair having a key 20.
However, you can also use the clear() method to remove all elements from the map.
<html><body><div>Map after deleting the [20,30] key-value pair:</div><div id ="demo"></div><script>const output = document.getElementById("demo");const map =newMap([[10,20],[20,30],[30,40]]);
map.delete(20);// Deleting a [20,30] key-value pair from the mapfor(let[key, value]of map)
output.innerHTML +="Key: "+ key +" Value: "+ value +"<br/>";</script></body></html></pre>
Output
Map after deleting the [20,30] key-value pair:
Key: 10 Value: 20
Key: 30 Value: 40
Example: Size of the Map
In the below code, we used the 'size' property of the Map class to get the total number of key-value pairs in the map.
<html><body><p id ="output">Size of the map object is:</p><script>const map =newMap();
The JavaScript WeakSet object is a collection of objects. The WeakSet is very similar to the Set. The main difference between the WeakSet and Set is that the WeakSet contains only objects, and the Set can also contain the values like numbers, Boolean, string, etc.
WeakSet objects are weak, meaning that references to objects in a WeakSet are held weakly. If no other references to a value stored in the WeakSet exist, those values can be garbage collected.
WeakSet objects are useful for keeping track of objects without preventing them from being garbage collected. An example of this would be keeping track of DOM nodes without having to remove them from the DOM manually.
Syntax
Follow the syntax below to define a new instance of the WeakSet class in JavaScript.
const weakest =newWeakSet([iterable]);
We used the WeakSet() constructor function with a ‘new’ keyword in the above syntax.
Parameters
iterable − It is an iterable containing multiple objects to initialize the WeakSet.
In JavaScript, if two objects contain the same properties and value, they are still different as their references are different.
Here, we have listed the methods and properties of the WeakSet.
WeakSet Properties
Here is a list of all the properties of WeakSet and their description.
Sr.No.
Property & Description
1
constructorIt returns the WeakSet constructor function.
WeakSet Methods
Here is a list of the methods associated with WeakSet object and their description.
Sr.No.
Methods & Description
1
add()To insert the object into the WeakSet.
2
delete()To delete a single object from the WeakSet.
3
has()Check whether a particular object exists in the WeakSet.
Examples
Example: Similar Objects with WeakSet
In the example below, we have defined the obj1 and obj2 empty objects and added them to the WeakSet.
Also, we used the has() method to check whether the set contains the obj1 and obj2 objects. Both objects look similar but have different references in the memory. So, the WeakSet contains both objects.
output.innerHTML +="The weak_set contains the obj1 object! <br>";}if(weak_set.has(obj2)){
output.innerHTML +="The weak_set contains the obj2 object! <br>";}</script></body></html></pre>
Output
The weak_set contains the obj1 object!
The weak_set contains the obj2 object!
Example: Add Object in WeakSet
In the example below, we have defined the WeakSet containing 0 elements. Also, we have defined the car object and used the add() method to add the object in the set.
After that, we use the has() method to check whether the object has been added into the WeakSet.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const weak_set =newWeakSet();const car ={
brand:"Audi",
model:"Q5",}
weak_set.add(car);if(weak_set.has(car)){
output.innerHTML ="The car object is added successfully to the weak_set.";}</script></body></html></pre>
Output
The car object is added successfully to the weak_set.
Example: Delete Object from the WeakSet
In the example below, we have initialized the WeakSet with the car object. After that, we use the delete() method to delete the object from the WeakSet.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const car ={
brand:"Audi",
model:"Q5",}const carWeakSet =newWeakSet([car]);const flag = carWeakSet.delete(car);// returns true if deleted successfully
output.innerHTML ="The car object is deleted successfully from the carWeakSet? "+ flag;</script></body></html></pre>
Output
The car object is deleted successfully from the carWeakSet? true
WeakSet is not iterable. So, you can't traverse through its elements.
A JavaScript Set object is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type. The sets are introduced to JavaScript in ECMAScript 6 (ES6).
JavaScript Sets are similar to Arrays, but there are some key differences:
Sets can only hold unique values, while Arrays can hold duplicate values.
Sets are not ordered, while Arrays are ordered.
Sets are faster to add and remove items from than Arrays.
JavaScript Sets are often used to store unique values, such as the unique users who have visited a website. They can also be used to remove duplicate values from an Array.
Syntax
Users can follow the syntax below to define a set in JavaScript −
let set1 =newSet([iterable]);
In the above syntax, we used the Set() constructor function with a new keyword to define a set.
Parameters
Iterable− It is an optional parameter. The Set() constructor function traverses through the elements of the iterable and creates a new set using those elements.
Examples
Example (Access set elements)
In the example below, we have passed the array containing the duplicate elements as an argument of the Set() constructor function. The num_set contains only unique values.
We used the values() method to get the iterator of the set values. To traverse the iterator, we use the for…of loop. In the loop, we access the element and print it. You can observe that set contains unique values even if the input array contains duplicate elements.
<html><body><p>The set elements are:</p><p id ="output"></p><script>const num_set =newSet([10,20,20,20]);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The set elements are:
10
20
Example (Insert elements into the sets)
Users can use the add() method to insert the element into the set. Here, we have created the empty set. After that, we used the add() method 3 times to add the 60, 50, 50 elements into the set.
We inserted the 50 for 2 times, but the set contains only once as it contains unique values.
<html><body><p>Set elements after adding element/s to it:</p><div id ="output"></div><script>const num_set =newSet();
num_set.add(60);
num_set.add(50);
num_set.add(50);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
Set elements after adding element/s to it:
60
50
Example (Remove set elements)
The delete() method of the set allows you to delete the element from the set. Here, we created the set containing the various numbers and used the delete() method to delete the 200 and 400 from the set.
<html><body><p> After deleting elements from the set:</p><div id ="output"></div><script>let num_set =newSet([100,200,300,400,500]);
num_set.delete(200);
num_set.delete(400);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The set contains 100?: true
Example (Check if the set contains a specific value)
The example below demonstrates of using the has() method to check whether the set contains the specific value.
Here, we check whether the set contains 100 and print the message in the output accordingly.
<html><body><p id ="output">The set contains 100?:</p><script>const num_set =newSet([100,200,300,400,500]);
It returns "true" because the element 100 is present in the set.
The set contains 100?: true
Mathematical set operations
The Set class doesnt contain the built-in methods to perform the mathematical set operations like union, intersection, or set difference. So, you need to write the custom JavaScript code to perform the mathematical operations as shown below.
Example (Union of two sets)
The union of two sets contains all unique elements of set1 and set2.
In the example below, set1 and set2 contain the car names. We have defined the union set and passed the array as an argument. We used the spread operator to create an array containing the elements of set1 and set2.
<html><body><p>The Union of set1 and set2 is:</p><div id ="output"></div><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TaTa","Honda","Suzuki"]);const union =newSet([...set1,...set2]);// Taking unionfor(let value of union.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
If we execute the program, it returns all unique elements of set1 and set2.
The Union of set1 and set2 is:
BMW
Audi
TATA
TaTa
Honda
Suzuki
Example (Intersection of two sets)
The intersection of two sets contains the unique elements which exist in set1 and set2 both.
Here, we have two sets containing the car names and defined the inter set to store the set elements which exist in both sets.
We traverse through the elements of set1, and inside the loop we use the has() method to check whether the element of the set1 exists in the set2. If yes, we add an element into the inter set.
<html><body><p> The intersection of set1 and set2 is:</p><p id ="output"></p><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TATA","Honda","Suzuki"]);const inter =newSet();for(let car of set1){if(set2.has(car)){
inter.add(car);}}for(let value of inter.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The intersection of set1 and set2 is:
BMW
TATA
Example (Difference of two sets)
The difference between set1 and set2 contains all elements in the set1 but not in the set2.
We have created the new set named diff and initialized it with the set1 elements. After that, we traverse the set2 elements. If any element of the set2 exists in the diff set, we delete it.
<html><body><p>The difference of set1 and set2 is:</p><div id ="output"></div><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TATA","Honda","Suzuki"]);const diff =newSet(set1);for(let car of set2){
diff.delete(car);}for(let value of diff.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The difference of set1 and set2 is:
Audi
JavaScript Set Reference
In JavaScript, a Set is a collection of unique values. In other words, each value can occur only once within a set. It provides methods to add, remove, and check for the presence of elements in the set. Here, we have listed the properties and methods of the Set class.
JavaScript Set Constructor()
Following is the constructor of Set in JavaScript −
Sr.No.
Name & Description
1
Set()Creates and returns the set of unique values from values passed as an argument.
In JavaScript, Symbol is a primitive data type and it was introduced in ECMAScript 6 (ES6). It can be created using the ‘Symbol’ constructor.
Symbols are immutable and unique, unlike to other primitive data types like strings or numbers. They are especially helpful in situations where a unique identifier is required since they offer a way to create private object properties and avoid naming conflicts. Here, we have listed the properties and methods related to the symbol.
The points given below you should keep in mind while using the symbol.
Each symbol contains unique values.
The symbol is immutable. It means you can’t update the value of the symbol.
Symbols are used to define unique object properties.
The type of the symbol can’t be changed.
Syntax
You can follow the syntax below to create a new symbol using the Symbol() function. −
const sym =Symbol([description]);
Here description is an optional parameter. It specifies the symbol description, which you can access using the ‘description’ property.
Symbol Properties
In the following table, we have listed all the properties of Symbol −
Sr.No.
Name & Description
1
descriptionTo get an optional description of the symbol object.
2
asyncIteratorIt changes the object to async iterable.
3
hasInstanceTo check whether the constructor object counts the object as its instance.
4
isConcatSpreadableIt determines that while using the array.concat() method array should be concatenated as an object or flattened array.
5
iteratorReturns an iterator of the symbol.
6
matchMatches the regular expression with the string.
7
matchAllReturns all matches of the regular expression with the string.
8
replaceTo replace a substring.
9
searchTo get an index of the matches value.
10
speciesTo create a derived object.
11
splitIt specifies the method that splits string from the indices where regular expression matches.
12
toStringTagTo create a default string description for the object.
Symbol Methods
In the following table, we have listed all the methods of Symbol −
document.getElementById("output").innerHTML ="The sym1 is: "+ sym1.toString()+"<br>"+"The type of sym1 is: "+typeof sym1 +"<br>";const sym2 =Symbol("description");
document.getElementById("output").innerHTML +="The sym2 is: "+ sym2.toString();</script></body></html></pre>
Output
When we execute the above script, it will generate an output consisting of the text displayed on the webpage.
The sym1 is: Symbol()
The type of sym1 is: symbol
The sym2 is: Symbol(description)
Example: Accessing Symbol Description
Let's look at the following example, where we are going to use the .description to get the description of the symbol.
<html><body><p id="output"></p><script>const sym =Symbol("Welcome to Tutorials Point...");
document.getElementById("output").innerHTML ="The sym description of the symbol is : "+ sym.description;</script></body></html></pre>
Output
On executing the above script, the output window will pop up, displaying the text on the webpage.
The sym description of the symbol is : Welcome to Tutorials Point...
Example: Each Symbol is Unique
In the example below, we have defined the sym1 and sym2 symbols. After that, we compare both variables and print the message accordingly.
Both symbols look similar but are different, which you can see in the output.
document.getElementById("output").innerHTML +="Sym1 and Sym2 are equal.";}else{
document.getElementById("output").innerHTML +="Sym1 and Sym2 are not equal.";}</script></body></html></pre>
Output
After executing, it returns a text indicating that the both the symbols are not equal.
Sym1 and Sym2 are not equal.
Example: Using Symbol as an Object Key
The main purpose of the symbol is to use it as an object key. Here, we have used the 'objId' symbol as a key.
When we print the object by converting it to string or traversing the object properties, it won't print the symbol. So, the symbol can help developers to make object properties private.
<html><body><p id="output">The object is:</p><script>const objId =Symbol();const person ={
If we execute the above program, it will generate an output consisting of the text displayed on the webpage.
The object is: {"name":"John Doe","age":30}
Benefits of using Symbols
Here, we have explained the benefits of using symbols in real-time development.
Unique property keys − Each symbol is unique, even if its description is different. So, you can use the symbol as a key to avoid accidental collision between the keys with the same name. Mainly, it is useful when you need to use the same instance of the object in two different code snippets and need to insert the same properties.
Non-iterable properties − When you add the symbol as a key in JavaScript and traverse the object properties using the for...in loop, the loop doesn't traverse through the symbol keys.
Private Members − You can use the symbol to define the private properties in JavaScript classes.
Avoid overWriting − The symbol is unique, so it avoids overwriting similar properties.
A regular expression (RegExp) in JavaScript is an object that describes a pattern of characters. It can contain the alphabetical, numeric, and special characters. Also, the regular expression pattern can have single or multiple characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.
The regular expression is used to search for the particular pattern in the string or replace the pattern with a new string.
There are two ways to construct the regular expression in JavaScript.
Using the RegExp() constructor.
Using the regular expression literal.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Parameters
Here is the description of the parameters −
pattern − A string that specifies the pattern of the regular expression or another regular expression.
attributes − An optional string containing any of the “g”, “i”, and “m” attributes that specify global, case-insensitive, and multi-line matches, respectively.
Before we learn examples of regular expression, let’s learn about regular expression modifiers, Quantifiers, literal characters, etc.
Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc.
Sr.No.
Modifier & Description
1
iPerform case-insensitive matching.
2
mSpecifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary
3
gPerforms a global matchthat is, find all matches rather than stopping after the first match.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
Sr.No.
Expression & Description
1
[…]Any one character between the brackets.
2
[^…]Any one character not between the brackets.
3
[0-9]It matches any decimal digit from 0 through 9.
4
[a-z]It matches any character from lowercase a through lowercase z.
5
[A-Z]It matches any character from uppercase A through uppercase Z.
6
[a-Z]It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.
Sr.No.
Expression & Description
1
p+It matches any string containing one or more p’s.
2
p*It matches any string containing zero or more p’s.
3
p?It matches any string containing at most one p.
4
p{N}It matches any string containing a sequence of N p’s
5
p{2,3}It matches any string containing a sequence of two or three p’s.
6
p{2, }It matches any string containing a sequence of at least two p’s.
7
p$It matches any string with p at the end of it.
8
^pIt matches any string with p at the beginning of it.
9
?!pIt matches any string which is not followed by a string p.
Examples
Following examples explain more about matching characters.
Sr.No.
Expression & Description
1
[^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z.
2
p.pIt matches any string containing p, followed by any character, in turn followed by another p.
3
^.{2}$It matches any string containing exactly two characters.
4
<b>(.*)</b>It matches any string enclosed within <b> and </b>.
5
p(hp)*It matches any string containing a p followed by zero or more instances of the sequence hp.
Literal characters
The literal characters can be used with a backslash (\) in the regular expression. They are used to insert special characters, such as tab, null, Unicode, etc., in the regular expression.
Sr.No.
Character & Description
1
AlphanumericItself
2
\0The NUL character (\u0000)
3
\tTab (\u0009
4
\nNewline (\u000A)
5
\vVertical tab (\u000B)
6
\fForm feed (\u000C)
7
\rCarriage return (\u000D)
8
\xnnThe Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n
9
\uxxxxThe Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t
10
\cXThe control character ^X; for example, \cJ is equivalent to the newline character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.
Sr.No.
Character & Description
1
.a single character
2
\sa whitespace character (space, tab, newline)
3
\Snon-whitespace character
4
\da digit (0-9)
5
\Da non-digit
6
\wa word character (a-z, A-Z, 0-9, _)
7
\Wa non-word character
8
[\b]a literal backspace (special case).
9
[aeiou]matches a single character in the given set
10
[^aeiou]matches a single character outside the given set
11
(foo|bar|baz)matches any of the alternatives specified
Let’s learn to create regular expressions below.
let exp =/tutorialspoint/i
/tutorialspoint/ It finds a match for the ‘tutorialspoint’ string.
i It ignores the case of the characters while matching the pattern with the string. So, it matches with ‘TutoiralsPoint’, or ‘TUTORIALSpoint’, etc.
let exp =/\d+/
\d It matches 0 to 9 digits.
+ It matches one or more numeric digits.
let exp =/^Hi/
^ – It matches the start of the text.
Hi It checks whether the text contains ‘Hi’ at the start.
Let exp =/^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/
The above regular expression validates the email. It looks complex, but it is very easy to understand.
^ – Start of the email address.
[a-zA-Z0-9] It should contain the alphanumeric characters in the start.
+ – It should contain at least one alphanumeric character.
@ – It must have the ‘@’ character after the alphanumeric characters.
[a-zA-Z]+ – After the ‘@’ character, it must contain at least 1 alphanumeric character.
\. It must contain a dot after that.
[a-zA-Z] After the dot, the email should contain alphabetical characters.
{2, 3} After the dot, it should contain only 2 or 3 alphabetical characters. It specifies the length.
$ – It represents the end of the pattern.
Now, the question is whether we can use the search() or replace() method to search or replace text in the string by passing the string as an argument; then what is the need for the regular expression?
The question is obvious. Let’s understand it via the example below.
Example
In the below example, we used the regular expression literal to define the regular expression. The pattern matches the ‘tutorialspoint’ string without comparing the case of characters.
In the first case, the string search() method searches for the ‘tutorialspoint’ string, which performs the case-sensitive match. So, it returns -1.
In the second case, we passed the regular expression as an argument of the search() method. It performs the case-insensitive match. So, it returns 11, the index of the required pattern.
<html><head><title> JavaScript - Regular Expression </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let pattern =/tutorialspoint/i;let str ="Welcome to TuTorialsPoint! It is a good website!";let res = str.search('tutorialspoint');
output.innerHTML +="Searching using the string : "+ res +"<br>";
res = str.search(pattern);
output.innerHTML +="Searching using the regular expression : "+ res;</script></body></html></pre>
Execute the program to see the desired results.
Example
In the example below, we used the replace() method to match the pattern and replace it with the '100' string.
Here, the pattern matches the pair of digits. The output shows that each number is replaced with '100' in the string. You may also add alphabetical characters in the string.
<html><head><title> JavaScript - Regular expression </title></head><body><p id ="output"></p><script>let pattern =/\d+/g;// Matches pair of digitslet str ="10, 20, 30, 40, 50";let res = str.replace(pattern,"100");
document.getElementById("output").innerHTML ="String after replacement : "+ res;</script></body></html></pre>
Execute the program to see the desired results.
Example (Email validation)
In the example below, we used the RegExp() constructor function with a 'new' keyword to create a regular expression. Also, we have passed the pattern in the string format as an argument of the constructor.
Here, we validate the email using the regular expression. In the first case, email is valid. In the second case, the email doesn't contain the @ character, so the test() method returns false.
<html><body><p id ="output"></p><script>const pattern =newRegExp('^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$');
document.getElementById("output").innerHTML ="[email protected] is valid? : "+ pattern.test('[email protected]')+"<br>"+"abcdgmail.com is valid? : "+ pattern.test('abcdgmail.com');</script></body></html></pre>
So, the regular expression can be used to find a particular pattern in the text and perform operations like replace.
RegExp Properties
Here is a list of the properties associated with RegExp and their description.
Sr.No.
Property & Description
1
constructorSpecifies the function that creates an object's prototype.
2
globalSpecifies if the "g" modifier is set.
3
ignoreCaseSpecifies if the "i" modifier is set.
4
lastIndexThe index at which to start the next match.
5
multilineSpecifies if the "m" modifier is set.
6
sourceThe text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
Sr.No.
Method & Description
1
exec()Executes a search for a match in its string parameter.
2
test()Tests for a match in its string parameter.
3
toSource()Returns an object literal representing the specified object; you can use this value to create a new object.
4
toString()Returns a string representing the specified object.
In the following sections, we will have a few examples to demonstrate the usage of RegExp methods.
The JavaScript math object provides properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument.
Syntax
The syntax to call the properties and methods of Math are as follows −
var pi_val = Math.PI;// Propertyvar sine_val = Math.sin(30);// Method
Lets learn more about the Math objects properties and method via the examples below.
JavaScript Math Properties
Following is the list of properties of Math class in JavaScript −
Sr.No.
Name & Description
1
EEuler’s constant and the base of natural logarithms, approximately 2.718.
2
LN2Natural logarithm of 2, approximately 0.693.
3
LN10Natural logarithm of 10, approximately 2.302.
4
LOG2EBase 2 logarithm of E, approximately 1.442.
5
LOG10EBase 10 logarithm of E, approximately 0.434.
6
PIThe ratio of a circle’s circumference to its diameter is approximately 3.14159.
7
SQRT1_2The square root of 1/2, equivalently, 1 over the square root of 2, is approximately 0.707.
8
SQRT2The square root of 2, approximately 1.414.
JavaScript Math Methods
Following is the list of methods of Math class in JavaScript −
Sr.No.
Name & Description
1
abs()Returns the absolute value of a number.
2
acos()Returns the arccosine (in radians) of a number.
3
acosh()Returns the inverse hyperbolic consine of a number.
4
asin()Returns the arcsine (in radians) of a number.
5
asinh()Returns the inverse hyperbolic sine of a number.
6
atan()Returns the arctangent (in radians) of a number.
7
atan2()Returns the arctangent of the quotient of its arguments.
8
atanh()Returns the inverse hyperbolic tangent of a number.
9
cbrt()Finds a cube root of a given number.
10
ceil()Returns the smallest integer greater than or equal to a number.
11
clz32()Returns the number of leading zero in 32-bit binary number.
12
cos()Returns the cosine of a number.
13
cosh()It returns the hyperbolic cosine of a number.
14
exp()Returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.
15
expm1()Returns EN – 1, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.
16
floor()Returns the largest integer less than or equal to a number.
17
fround()Returns a nearest 32-bit single precision float representation of the number.
18
hypot()Calculates the square root of the sum of squares of arguments.
19
imul()Calculates the 32-bit multiplication of parameters.
20
log()Returns the natural logarithm (base E) of a number.
21
log10()Returns the logarithm (base 10) of a number.
22
log1p()Return the natural logarithm (base E) of 1 + N, where N is an argument.
23
log2()Returns the base 2 logrithm of a number.
24
max()Returns the largest of zero or more numbers.
25
min()Returns the smallest of zero or more numbers.
26
pow()Returns base to the exponent power that is, base exponent.
27
random()Returns a pseudo-random number between 0 and 1.
28
round()Returns the value of a number rounded to the nearest integer.
29
sign()Return -1 or 1 indicating the sign of the number.
30
sin()Returns the sine of a number.
31
sinh()Return the hyperbolic sin.
32
sqrt()Returns the square root of a number.
33
tan()Returns the tangent of a number.
34
tanh()Returns the hyperbolic tangent of the number.
35
trunc()Returns the integer part of the number.
In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.
Example (Math object Properties)
The example below demonstrates that each property of the Math object has a constant value.
Here, we have accessed the values of the E, LN2, and PI properties.
After executing the above program, it returns the values of the provided Math properties.
Example (Math ceil() method)
Here, we are computing the JavaScript ceil() method to return the smallest larger integer value than the number passed as an argument. Here, the method returns 6 for the 5.9 value.
<html><head><title> JavaScript - Math.ceil() method </title></head><body><p id ="output"></p><script>let ans = Math.ceil(5.9);
document.getElementById("output").innerHTML ="Math.ceil(5.9) = "+ ans;</script></body></html>
Output
After executing the above program, it returns the result as 6.
Example (Math max() method)
The Math.max() method is used to get the maximum value among the arguments passed as an array.
Here, we have passed six arguments to the Math.max() object, and the method returns the maximum value from them.
<html><head><title> JavaScript - Math.max() method </title></head><body><p id ="output"></p><script>let ans = Math.max(100,10,-5,89,201,300);
document.getElementById("output").innerHTML ="Math.max(100, 10, -5, 89, 201, 300) = "+ ans +"<br>";</script></body></html>
Output
After executing the above program, it returns 300 as maximum value.
Example (Math.cos() method)
The Math.cos() method returns the cosine value of the number passed as an argument. The cosine value of 0 is 1, which you can see in the output of the example below.
<html><head><title> JavaScript - Math.cos() method </title></head><body><p id ="output"></p><script>let ans = Math.cos(0);
document.getElementById("output").innerHTML ="Math.cos(0) = "+ ans;</script></body></html>
Output
If we execute the above program, it returns “1” as result.
The JavaScript Proxy Handlers are used to define custom behavior for fundamental operations performed on objects. By defining handlers, you can override the default behavior of fundamental operations. Following are the common proxy handler methods: apply(), construct(), get(), has(), etc.
JavaScript Handlers
Following are the methods of JavaScript Handler −
Sr.No.
Name & Description
1
apply()Allows you call a function with particular arguments and context.
2
construct()Allows you to define custom behavior for fundamental operations on an object.
3
defineproperty()It is used to define new properties or modify existing ones on an object.
4
deleteproperty()It is used as a trap for the delete operator.
5
get()It is a trap for getting a property value.
6
getownpropertydescriptor()It is a trap for the [[GetOwnProperty]] object internal method.
7
getprototypeof()It is a trap for the internal method.
8
has()It is used to hide any property that you want.
9
isextensible()It is used to determine whether the new property can be added or not the target object.
10
ownkeys()It is a trap for the [[OwnPropertyKeys]] object internal method.
11
set()It is a trap for the [[Set]] object internal method.
12
setprototypeof()Allows you set the prototype of a specified object to another object to another object.
TheDataViewis an object in JavaScript that allows you to work with the binary data stored in theArrayBuffer. It provides a low-level interface for reading and writing number types in a binary ArrayBuffer.
The DataView object provides built-in methods for reading and writing 1, 2, and 4-byte signed and unsigned integers, as well as 4 and 8-byte floating-point numbers from the buffer.
An ArrayBuffer is an array of bytes, usually referred to in other languages as a “byte array”. You cannot directly manipulate the data of an ArrayBuffer like a regular array. Using the ArrayBuffer you can create DataView object, which represents the buffer in a specific format. You can use the DataView object to read from and write to the contents of the buffer.
Syntax
Following is the syntax to create a DataView object in JavaScript −
newDataView(buffer, byteOffset, byteLength)
Here, the buffer is an existing ArrayBuffer used for storage. The byteOffset parameter (optional) represents the offset in bytes to the first byte in the buffer, and the byteLength parameter (also optional) represents the number of elements in the byte array.
Example : Creating a DataView Object
The following example demonstrates how to create a DataView object in JavaScript.
<html><body><script>const buffer =newArrayBuffer(16);//creating dataview objectconst data_view =newDataView(buffer);
document.write("The type of data_view is: "+typeof(data_view));</script></body></html>
Output
The above program displays the type of the data_view as −
The type of data_view is: object
JavaScript DataView Properties
Here is a list of the properties of DataView object −
buffer − It returns the ArrayBuffer of SharedArrayBuffer.
byteLength − It returns the length (in bytes) of this view.
byteOffset − It returns the offset (in bytes) of this view from the start of itsArrayBufferorSharedArrayBuffer.
JavaScript DataView Methods
Following are the methods of the JavaScript DataView object −
Sr.No.
Methods & Description
1
getBigInt64()It returns a BigInt from the range of -263 to 263-1, included.
2
getBigUint64()It returns a BigInt from the range of 0 to 264-1, included.
3
getFloat32()It returns a floating point number from -3.4e38 to 3.4e38.
4
getFloat64()It returns any number value.
5
getInt16()It returns an integer from -32768 to 32767, included.
6
getInt32()It returns an integer from the range of -2147483648 to 2147483647, included.
7
getInt8()It returns an integer from the range of -128 to 127, included.
8
getUint16()It returns an integer from the range of 0 to 65535, included.
9
getUint32()It returns an integer from the range of 0 to 4294967295, included.
10
getUint8()It returns an integer from the range of 0 to 255, included.
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent the date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using the Date() constructor −
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
Parameters
No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
datestring − When one string argument is passed, it is a string representation of a date in the format accepted by the Date.parse() method.
7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998 rather than 98.
month − Integer value representing the month, beginning with 0 for January to 11 for December.
date − Integer value representing the day of the month.
hour − Integer value representing the hour of the day (24-hour scale).
minute − Integer value representing the minute segment of a time reading.
second − Integer value representing the second segment of a time reading.
millisecond − Integer value representing the millisecond segment of a time reading.
Return Value
It returns the date string containing day, month, date, year, hours, minutes, seconds, and timezone, as shown below.
Wed Aug 09 2023 09:24:03 GMT+0530 (India Standard Time)
JavaScript Date Reference
In JavaScript, the Date object provides methods for creating, manipulating, and formatting dates and times. Here, we have listed all the methods present in Date class −
JavaScript Date Methods
Here is a list of the methods used with Date and their description.
Date Static Methods
These methods are invoked using the Date object −
Sr.No.
Name & Description
1
Date.parse()Parses a string representation of a date and time and returns the internal millisecond representation of that date.
2
Date.UTC()Returns the millisecond representation of the specified UTC date and time.
Date Methods
These methods are invoked using the instance of the Date object −
Sr.No.
Name & Description
1
getDate()Returns the day of the month for the specified date according to local time.
2
getDay()Returns the day of the week for the specified date according to local time.
3
getFullYear()Returns the year of the specified date according to local time.
4
getHours()Returns the hour in the specified date according to local time.
5
getMilliseconds()Returns the milliseconds in the specified date according to local time.
6
getMinutes()Returns the minutes in the specified date according to local time.
7
getMonth()Returns the month in the specified date according to local time.
8
getSeconds()Returns the seconds in the specified date according to local time.
9
getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
10
getTimezoneOffset()Returns the time-zone offset in minutes for the current locale.
11
getUTCDate()Returns the day (date) of the month in the specified date according to universal time.
12
getUTCDay()Returns the day of the week in the specified date according to universal time.
13
getUTCFullYear()Returns the year in the specified date according to universal time.
14
getUTCHours()Returns the hours in the specified date according to universal time.
15
getUTCMilliseconds()Returns the milliseconds in the specified date according to universal time.
16
getUTCMinutes()Returns the minutes in the specified date according to universal time.
17
getUTCMonth()Returns the month in the specified date according to universal time.
18
getUTCSeconds()Returns the seconds in the specified date according to universal time.
19
setDate()Sets the day of the month for a specified date according to local time.
20
setFullYear()Sets the full year for a specified date according to local time.
21
setHours()Sets the hours for a specified date according to local time.
22
setMilliseconds()Sets the milliseconds for a specified date according to local time.
23
setMinutes()Sets the minutes for a specified date according to local time.
24
setMonth()Sets the month for a specified date according to local time.
25
setSeconds()Sets the seconds for a specified date according to local time.
26
setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
27
setUTCDate()Sets the day of the month for a specified date according to universal time.
28
setUTCFullYear()Sets the full year for a specified date according to universal time.
29
setUTCHours()Sets the hour for a specified date according to universal time.
30
setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.
31
setUTCMinutes()Sets the minutes for a specified date according to universal time.
32
setUTCMonth()Sets the month for a specified date according to universal time.
33
setUTCSeconds()Sets the seconds for a specified date according to universal time.
34
toDateString()Returns the “date” portion of the Date as a human-readable string.
35
toISOString()Returns date string in the ISO format.
36
toLocaleDateString()Returns the “date” portion of the Date as a string, using the current locale’s conventions.
37
toJSON()Converts a date to a string.
38
toLocaleString()Converts a date to a string, using the current locale’s conventions.
39
toLocaleTimeString()Returns the “time” portion of the Date as a string, using the current locale’s conventions.
40
toString()Returns a string representing the specified Date object.
41
toTimeString()Returns the “time” portion of the Date as a human-readable string.
42
toUTCString()Converts a date to a string, using the universal time convention.
43
valueOf()Returns the primitive value of a Date object.
Date Object Constructor
Following is the Date Object Constructor in JavaScript −
Sr.No.
Name & Description
1
Date()Returns today’s date and time.
Example: Creating JavaScript Date Object
In the example below, we create a new instance of the date object. In the output, you can observe that it returns the current time.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date();
document.getElementById("output").innerHTML =
"Today's date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the current time.
Example: Setting up custom date
In the example below, We have passed the custom date string as a parameter of the Date() constructor to create a custom date.
The Date() constructor returns the standard date string, which you can see in the output.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date("August 19, 2024 09:30:54");
document.getElementById("output").innerHTML =
"The custom date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the custom time as provided.
Example
In the example below, we have passed milliseconds as an argument of the Date() constructor. If you pass the positive milliseconds as an argument, the object returns the date according to the 1st January 1970 00:00:00 + milliseconds.
Otherwise, it returns the date according to the 1st January 1970 00:00:00 milliseconds if negative milliseconds passed as an argument.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const output = document.getElementById("output");
let date = new Date(999999999999);
output.innerHTML += "The Date after 1st January, 1970 is - " + date + "<br>";
date = new Date(-999999999999);
output.innerHTML += "The Date before 1st January, 1970 is - " + date;
</script></body></html>
Output
It returns the date after 1st January, 1970 and before 1st January, 1970 as result.
Example: Constructing a date from 7 arguments
In the example below, we have passed the year, month, date, hour, minute, second, and millisecond as a Date() constructor argument. The Date() constructor returns the full date string, which you can see in the output.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date(2001, 5, 14, 6, 43, 58, 342);
document.getElementById("output").innerHTML =
"The custom date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the custom time as provided.
However, you can use the different methods of the Date object to format the date string. Lets look at the example below.
Example: Formatting a date string
In the example below, three different methods are used to format the date string.
The toDateString() method extracts the date only from the date string and removes the time part.
The toISOString() method converts the date string into the ISO format.
The toUTCString() method converts the date string into the UTC time format.
<html><head><title> JavaScript - Formatting the date </title></head><body><p id = "output"></p><script>
const date = new Date(999999999999);
document.getElementById("output").innerHTML +=
"The Date after 1st January, 1970 is: " + date.toDateString() + "<br>"+
"The Date after 1st January, 1970 is: " + date.toISOString() + "<br>"+
"The Date after 1st January, 1970 is: " + date.toUTCString();
</script></body></html>
Output
It will return the ouptut of the above provided methods, respectively.