0% found this document useful (0 votes)
5 views

javascript notes

This tutorial explains user-defined object types in JavaScript, including how to create them using constructor functions and the Object.create method. It also covers the JavaScript Date object, detailing its creation, manipulation, and built-in methods for handling dates and times. Additionally, the tutorial introduces the JavaScript RegExp object for pattern matching and validation in strings, providing examples of its usage and properties.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

javascript notes

This tutorial explains user-defined object types in JavaScript, including how to create them using constructor functions and the Object.create method. It also covers the JavaScript Date object, detailing its creation, manipulation, and built-in methods for handling dates and times. Additionally, the tutorial introduces the JavaScript RegExp object for pattern matching and validation in strings, providing examples of its usage and properties.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

JavaScript User-

defined Object Type


This tutorial covers the concept of the user-defined object type in
JavaScript. We have already covered JavaScript object which is created
using object initializer syntax or the Object constructor syntax, and
instance of an Object type is created.
Creating User-defined JavaScript Object Type

We can define a custom object type by writing a constructor function


where the name of the function should start with an uppercase alphabet fo
example Car, Cup, Human, etc.
The constructor function is defined just as we define any other user-
defined JavaScript Function.
Here is the syntax for defining a constructor function:

function Xyz(param1, param2, ... , paramN)


{
this.param1 = param1;
this.param2 = param2;
...
this.paramN = paramN;
}
let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);

Using this Keyword

In JavaScript we use this keyword to reference the current object, henc


the constructor function we create new properties (param1, param2, ...) for
the object type and we set the values for the parameters provided at the ti
of object creation using the new keyword.

<!doctype html>
<head>
<title>Create User-defined Object in JavaScript</title>
</head>
<body>
<script>
/* defining a new constructor function */
function Bike(company, model, year) {
this.company = company;
this.model = model;
this.year = year;
}

/* creating the object */


let myBike = new Bike("KTM", "Duke", 2010);
document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year);
</script>
</body>
</html>

Using the Object.create method

If you do not want to get into the trouble of defining a constructor


method to define a user-defined object type, you can use the Object.create
method to create an object of any prototype object which is already defined
Let's take an example to understand this.
let Bike = {
company: 'KTM', // Default value of properties
model: 'Duke 390',
show: function() { // Method to display property type of Bike
document.write(this.company+" "+this.model);
}
};

// using Object.create to create a new object


let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();
output:
Yamaha R15
As you can see in the code above, we can use the Object.create method t
create a new object using an already defined object, and then if required w
can change the properties values and use the object function too.
JavaScript Date Objec
JavaScript Date object is a built-in object which is used to deal with da
and time. It stores a Number which represents milliseconds for the Unix
Timestamp(which is nothing but milliseconds passed since 1 January 1970
UTC). We can use it to create a new date, format a date, get elapsed time
between two different time values, etc.
It also helps to get a date value using milliseconds number and we can
get a date based on the different timezones as well.
The Date object use browser's date timezone by default and display d
in the text format.
The Date object can be created using the Date constructor function.
Creating the JavaScript Date Object

Let's see how we can create the Date object in JavaScript. Although
there are multiple ways of doing it, the default way is using the new keyword
with the Date constructor function.

let newdate = new Date();


The above will create a new Date object with the current date and tim
stored in it. The format of the date stored in this object will be:

Tue May 05 2020 21:16:17 GMT+0530 (India Standard Time)


Yes, it will be the complete date and time along with timezone
information.
To get the standard UNIX timestamp value we can use the following
code:
let newdate = Date.now();
Copy

1588693792007
In the code above we have used the static function now() for the Date
object. This will give us the Unix timestamp for current date and time which
nothing but the number of milliseconds passed since 1 January 1970.

Other Ways to Create JavaScript Date

Apart from the above two syntaxes, there are multiple other ways to
create a date in JavaScript. Here, we are using different syntax to create da
objects.
<!doctype html>
<head>
<title>JS Date Example</title>
</head>
<body>
<script>
/* JS comes here */
let date1 = new Date('February 13, 1991 06:44:00');
let date2 = new Date('1991-02-13T06:44:00');
let date3 = new Date(1991, 02, 13); // the month is 0 indexe
let date4 = new Date(1991, 02, 13, 6, 44, 0);
document.write("Example 1: " + date1);
document.write("<br/>Example 2: " + date2);
document.write("<br/>Example 3: " + date3);
document.write("<br/>Example 4: " + date4);
</script>
</body>
</html>
As you can see in the examples above, we can create a date for a
custom date which can be a past date or a future date. We can even provid
the time value.
Working with JavaScript Date

JavaScript Date constructor handles different formats to create a date


we can pass a string format date or a numerical literal with milliseconds to
create a date object in JavaScript.

Creating JavaScript Date using String

JavaScript allows the following string formats to create a date object.


let date1 = new Date('February 13, 1991 06:44:00')
document.write(date1 +"<br>");

let date2 = new Date('1991-02-13T06:44:00');


document.write(date2);
Copy

Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time)


Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time)

Creating JavaScript Date using Numerical Literal

We can use the Date() constructor can take 7 arguments to create a


date, which is: year, month, day, hour, minute, second, and millisecon
We can also get a date by just passing milliseconds too. See the belo
example:
let date1 = new Date(2018,11,25,12,25,12,0);
document.write(date1 +"<br/>");
// Passing miliseconds
let date2 = new Date(1825356800000);
document.write(date2);
Copy

Tue Dec 25 2018 12:25:12 GMT+0530 (India Standard Time)


Fri Nov 05 2027 01:03:20 GMT+0530 (India Standard Time)

Get Year, Month and Day from a JavaScript Date

To get the value for the year, month or day from a date, we can use
JavaScript built-in methods. These methods are easy to use and reduce the
effort and time for coding.
// Creating a date
let date1 = new Date(2018,11,25,12,25,12,0);

// Getting year
let year = date1.getFullYear();
document.write("<br> Year: "+ year);

// Getting Month
let month = date1.getMonth();
document.write("<br> Month: "+ month);
// Getting day
let day = date1.getDate();
document.write("<br> Day: "+ day);
Copy

Year: 2018
Month: 11
Day: 25

JavaScript Date Object Methods

JavaScript provides a rich set of built-in methods which are both stati
and instance methods that can be used to get different information from
JavaScript Date object.
Method Description

Returns the number of milliseconds(Unix timestamp) for


Date.now()
the current date and time.

Parses a string value of date and returns the number of


milliseconds since 1 January 1970, 00:00:00 UTC, with leap
Date.parse()
seconds ignored.

This function takes 7 parameters with numeric values but


Date.UTC()
creates the date in UTC timezone.
Method Description

setDate() sets the date of the month that ranges from 1 to 31.

setHours() set hours that range from 0 to 23

getSeconds() returns the seconds that range from 0 to 59

toDateString() converts a date value into a string

returns the primitive value of Date object.


valueOf()
Method Description

setMinutes() set minutes that range from 0 to 59.

setMonth() set numerical equivalence of month range from 0 to 11

setMilliseconds()set the milliseconds that range from 0 to 999

toTimeString() converts time into a string.


getDate() returns the day of the month from 1 - 31
getDay() returns the day of the week from 0 - 6
Method Description

getFullYear() returns the year (4 digits for 4-digit years) of the


specified date
getMinutes() returns the minutes (0–59) in the specified date
getMonth() returns the month (0–11) in the specified date
getHours() returns the hours that that range from 0 to 23.

Now we are going to show you how to use some of the Date Object
methods:
<html>
<head>
<title>
Working with Date object
</title>
</head>
<body>
<script type="text/javaScript">
var mydate = new Date();
document.write("Today date is: " + mydate.getDate()+"/"+
(mydate.getMonth()+1)+"/"+mydate.getFullYear()+"<br/>");
document.write("The time is: " + mydate.getHours()
+":"+mydate.getMinutes()+":"+mydate.getSeconds()+"<br/>");
</script>
</body>
</html>

Finding the difference between JavaScript Date - Elapsed Time

We can simply subtract two dates to find the difference between any t
dates. Let's take an example to see this:
// Using Date objects
let start = Date.now();

// Do something for some time

// get the end time


let end = Date.now();
// time elapsed
let elapsed = end - start; // elapsed time in millisecond
Copy
But it's not that simple as a Date object has a day, month, year, hour,
minute and second values, hence we should take care while finding the
elapsed time.
In this tutorial, we covered the Date object in JavaScript which is used
many web applications.
JavaScript RegExp
Object
The regular expression or JavaScript RegExp is an object that helps yo
to validate the pattern of characters in a string or match a string, etc. You c
use the JavaScript RegExp object to validate an e-mail entered in a form, or
maybe check if a Pincode is all numeric, or a password has alphanumeric a
special characters, etc.
There are two ways of defining regular expression in JavaScript.
1. Using the JavaScript RegExp object's constructor function
2. Using Literal syntax
Creating JavaScript RegExp Object

Let's see how we can create a RegExp object in JavaScript:


// Object Syntax
let regExp = new RegExp("pattern", "flag");

// Literal Syntax
let regExp = /pattern/flag;
Copy
Where the pattern is the text of regular expression, the flag makes t
regular expression search for a specific pattern.
Note: In this tutorial, we will discuss the RegExp object, its properties
and methods. All the examples will be based on the RegExp object, not the
literal regular expression. We have covered the regex literal syntax earlier.
We will be using the following String methods to use the RegExp objec
to test, match, and validate various string values in JavaScript:
 test()

 match()

 replace()

 exec()

Let's take a few examples to understand the use of the JavaScript


RegExp object.
Creating a RegExp to match IP address

To match all the strings that look like IP address: xxx.xxx.xxx.xxx, w


can use the following regex
let regularexp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g;

Now let's create an example to validate an IP address. The below code


returns true if the given IP address is valid:
let str = "102.235.251.251";
// regex pattern to match valid ip
let re = new RegExp(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\
b/);
// test the regex
let result = re.test(str);
if(result)
document.write("Ip address is valid");
else
document.write("Ip address is not valid");

Copy

Ip address is valid

How to replace a string using Regex?

Let's see an example to replace a part of the string or the complete


string with some other string or replace the order of the string using a regu
expression.
// Creating regex object
let re = new RegExp(/(\w+)\s(\w+)/);
let str = 'Mohan Shyam';
// Replacing string
let newstr = str.replace(re, '$2, $1');
document.write(newstr);
Copy

Shyam, Mohan
Fetch Subdomain Value from a Domain Name

We can use a regular expression to fetch the subdomain from a URL. T


RegExp exec() method is used to perform regular expression pattern matchin
and return an array of string. See the below example:
let url = 'http://linux.studytonight.com';
// Creating regex object
let re = new RegExp(/[^.]+/);
let result = re.exec(url)[0].substr(7);
document.write(result);
Copy

linux
Find a Pattern in String

To find a pattern in string, we can use the string match() method. It retu
the match pattern that can be a substring. See the below example:
// Creating regex object
var regex = new RegExp(/India/g);
var str = "We live in India.";
// search for India
var matches = str.match(regex);
document.write(matches);
Copy
India

Properties of JavaScript RegExp Object

 global: refers that g modifier is set.


 ignoreCase: refers that i modifier is set
 lastIndex: refers to the index to start the next match.
 multiline: Refers that m modifier is set.
 source: refers to the text of the RegExp pattern.

JavaScript RegExp ignoreCase Property:

The ignoreCase property indicates whether or not the i flag is used with th
regular expression. The ignoreCase is a read-only property of the RegExp obje
var re = new RegExp("/hello/","i");
// ignorecase property
var result = re.ignoreCase;
document.write(result);
Copy

true

You might also like