You are on page 1of 85

JavaScript Objects

JavaScript Objects
• JS Object
• JS Array 
• JS String
• JS Date
• JS Math
• JS Number
• JS Boolean
JavaScript Objects
• A javaScript object is an entity having state and behavior
(properties and method).

• For example: car, pen, bike, chair, glass, keyboard, monitor etc.

• JavaScript is an object-based language. Everything is an object in


JavaScript.

• JavaScript is template based not class based. Here, we don't


create class to get the object. But, we direct create objects.
Creating Objects in JavaScript
• There are 3 ways to create objects.
• By object literal
• By creating instance of Object directly (using new keyword)
• By using an object constructor (using new keyword)
1) JavaScript Object by object literal

• The syntax of creating object using object literal is given below:


• object={property1:value1,property2:value2.....propertyN:valueN} 
• As you can see, property and value is separated by : (colon).
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000,age:20}
document.write(emp.id+" "+emp.name+" "+emp.salary+”
“+emp.age);
</script>
</body>
</html>
2) By creating instance of Object

• The syntax of creating object directly is given below:


• var objectname=new Object();  
• Here, new keyword is used to create object.

<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>  
3) By using an Object constructor
• Here, you need to create function with arguments.
• Each argument value can be assigned in the current object by using this
keyword.
• The this keyword refers to the current object.

<script>  
function emp(id,name,salary){  
this.id=id;  
this.name=name;  
this.salary=salary;  
}  
e=new emp(103,"Vimal Jaiswal",30000);  
  
document.write(e.id+" "+e.name+" "+e.salary);  
</script>  
JAVASCRIPT ARRAY
JavaScript Array
• An array is a special variable, which can hold more than
one value, at a time.
• If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
• cars1=“Honda";
cars2=“Suzuki";
cars3="BMW";
• An array can hold all your variable values under a single
name.
• Can access the values by referring to the array name.
• Each element in the array has its own ID so that it can be
easily accessed.
JavaScript Array
• JavaScript array is an object that represents a collection of
similar type of elements.
• There are 3 ways to construct array in JavaScript
• By array literal
• By creating instance of Array directly (using new keyword)
• By using an Array constructor (using new keyword)
1) JavaScript array literal
• The syntax of creating array using array literal is given below:
• var arrayname=[value1,value2.....valueN];  
• As you can see, values are contained inside [ ] and separated by ,
(comma).
• Let's see the simple example of creating and using array in
JavaScript.
<script>  
var emp=["Sonoo","Vimal","Ratan"];  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br/>");  
}  
</script>  
2) JavaScript Array directly (new keyword)
• The syntax of creating array directly is given below:
• var arrayname=new Array();  
• Here, new keyword is used to create instance of array.

<script>  
var i;  
var emp = new Array();  
emp[0] = "Arun";  
emp[1] = "Varun";  
emp[2] = "John";  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br>");  
}  
</script>  
3) JavaScript array constructor (new keyword)

• Here, you need to create instance of array by passing


arguments in constructor so that we don't have to provide
value explicitly.
• The example of creating object by array constructor is given
below.
<script>  
var emp=new Array("Jai","Vijay","Smith");  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br>");  
}  
</script>  
Access an Array

You can refer to a particular element in an array by referring to the name of


the array and the index number. The index number starts at 0.

The following code line:

document.write(myCars[0]);
will result in the following output:

Honda
JavaScript Array Methods
Methods Description

concat() It returns a new array object that contains two or more


merged arrays.
join() It joins the elements of an array as a string.
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

shift() It removes and returns the first element of an array.


sort() It returns the element of the given array in a sorted
order.
toString() It converts the elements of a specified array into string
form, without affecting the original array.
unshift() It adds one or more elements in the beginning of the
given array.
Array Functions

Join two arrays - concat()

var parents = [“Dad", “Mom"];


var children = [“Son", “Daughter"];
var family = parents.concat(children);
document.write(family);

Output:

Dad,Mom,Son,Daughter
Array Functions (Continue..)

Join three arrays - concat()

var parents = [“Dad", “Mom"];


var brothers = [“Chachu 1", “Chachu 2”];
var children = [“Son", “Daughter"];
var family = parents.concat(brothers, children);
document.write(family);

Output:

Dad,Mom,Chachu 1,Chachu 2,Son,Daughter


Array Functions (Continue..)

Join all elements of an array into a string - join()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));

Output:

Banana,Orange,Apple,Mango
Banana+Orange+Apple+Mango
Banana and Orange and Apple and Mango
Array Functions (Continue..)

Remove the last element of an array - pop()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.pop() + "<br />");
document.write(fruits + "<br />");
document.write(fruits.pop() + "<br />");
document.write(fruits);

Output:

Mango
Banana,Orange,Apple
Apple
Banana,Orange
Array Functions (Continue..)

Add new elements to the end of an array - push()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.push("Kiwi") + "<br />");
document.write(fruits.push("Lemon","Pineapple") + "<br />");
document.write(fruits);

Output:

5
7
Banana,Orange,Apple,Mango,Kiwi,Lemon,Pineapple
Reverse the order of the elements in an array - reverse()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.reverse());

Output:

Mango,Apple,Orange,Banana
Remove the first element of an array - shift()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.shift() + "<br />");
document.write(fruits + "<br />");
document.write(fruits.shift() + "<br />");
document.write(fruits);

Output:

Banana
Orange,Apple,Mango
Orange
Apple,Mango
Add new elements to the beginning of an array - unshift()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.unshift(“Grapes") + "<br />");
document.write(fruits.unshift("Lemon","Pineapple") + "<br/>");
document.write(fruits);

Output:

undefined
undefined
Lemon,Pineapple,Grapes,Banana,Orange,Apple,Mango

Note: The unshift() method does not work properly in


Internet Explorer, it only returns undefined!
Sort an array (alphabetically and ascending) - sort()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.sort());

Output:

Apple,Banana,Mango,Orange
Convert an array to a string - toString()

var fruits = ["Banana", "Orange", "Apple", "Mango"];


document.write(fruits.toString());

Output:

Banana,Orange,Apple,Mango
<!DOCTYPE html>
<html>
<body>

<script>
var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"];
var result=arr.splice(2,4);
document.writeln("Updated array: "+arr+"<br>");
document.writeln("Removed element: "+result);
</script>

</body>
</html>
The For/In Loop
• The JavaScript for/in statement loops through the properties
of an Object:
• Syntax
• for (key in object) {
  // code block to be executed
}
• Example
• var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
  text += person[x];
}
Example Explained
• The for in loop iterates over a person object
• Each iteration returns a key (x)
• The key is used to access the value of the key
• The value of the key is person[x]
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For/In Loop</h2>

<p>The for/in statement loops through the properties of an object.</p>

<p id="demo"></p>

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In</h2>

<p>The for/in statement can loops over Array values.</p>

<p id="demo"></p>

<script>
var txt = "";
var numbers = [45, 4, 9, 16, 25];
var x;
for (x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>
Array Properties
Property Description

constructor Returns a reference to the array function that created the


object.

length Reflects the number of elements in an array.

prototype The prototype property allows you to add properties and


methods to an object.
Constructor & length
<html>
<head>
<title>JavaScript Array constructor Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.constructor is:" + arr.constructor);
document.write("arr.length is : " + arr.length);
</script>
</body>
</html>
Prototype
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author)
{ this.title = title; this.author = author; }
</script> </head> <body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script> </body></html>
JS NUMBER OBJECT
JavaScript Number Object
• The JavaScript number object enables you to represent a
numeric value.
• It may be integer or floating-point.
• JavaScript number object follows IEEE standard to represent
the floating-point numbers.
• By the help of Number() constructor, you can create number
object in JavaScript.
• For example:
• var n=new Number(value);  
JS Number Object
• The Number object represents numerical date, either integers
or floating-point numbers.

• In general, you do not need to worry about Number objects


because the browser automatically converts number literals to
instances of the number class.

• Syntax:

• Creating a number object:


• var val = new Number(number);

• If the argument cannot be converted into a number, it returns


NaN (Not-a-Number).
JavaScript Number Constants
• Let's see the list of JavaScript number constants
with description.
Property Description

MAX_VALUE
The largest possible value a number in JavaScript can have
1.7976931348623157E+308

MIN_VALUE
The smallest possible value a number in JavaScript can have
5E-324

NaN Equal to a value that is not a number.


NEGATIVE_INFINITY A value that is less than MIN_VALUE.
POSITIVE_INFINITY A value that is greater than MAX_VALUE
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Object Properties</h2>

<p>MAX_VALUE returns the largest possible number in


JavaScript.</p>

<p id="demo"></p>

<script>
var x = Number.MAX_VALUE;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>
MAX_VALUE

<html>
<head>
<script type="text/javascript">
function showValue()
{ var val = Number.MAX_VALUE;
alert("Value of Number.MAX_VALUE : " + val );
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();" />
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Object Properties</h2>

<script>
document.write("Max value of number "+Number.MAX_VALUE+"<br>");

document.write("Min value of number "+Number.MIN_VALUE+"<br>");

document.write("POSITIVE_INFINITY value of number


"+Number.POSITIVE_INFINITY+"<br>");

document.write("NEGATIVE_INFINITY value of number


"+Number.NEGATIVE_INFINITY+"<br>");

document.write("NaN value of number "+Number.NaN+"<br>");


</script>
</body>
</html>
JavaScript Number Methods
• The Number object contains only the default methods that are part of every
object's definition.

Method Description

Forces a number to display in exponential notation, even if the number is in


toExponential()
the range in which JavaScript normally uses standard notation.

Formats a number with a specific number of digits to the right of the


toFixed() decimal.
isFinite() It determines whether the given value is a finite number.

toPrecision() Defines how many total digits (including digits to the left and right of the
decimal) to display of a number.

toString() Returns the string representation of the number's value.


isInteger() It determines whether the given value is an integer.
parseFloat() It converts the given string into a floating point number.
parseInt() It converts the given string into an integer number.
<html><head><title>Javascript Method toExponential()</title></head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");

val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");

val = num.toExponential(2);
document.write("num.toExponential(2) is : " + val);
document.write("<br />");

val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");
val = 77.1234.toExponential();
document.write("77 .toExponential() is : " + val);
</script></body></html>
<!DOCTYPE html> <html> <body> <script>
var a="50";
var b="51.25"
document.writeln(Number.isInteger(1)+"<BR>");
document.writeln(Number.isFinite(Infinity));

document.writeln("<BR>"+Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");

document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
var c=989721;
document.writeln(c.toExponential(2)+"<br>");
document.writeln(c.toExponential(4)+"<br>");
var d=98.9721;
document.writeln(d.toFixed()+"<br>");
document.writeln(d.toFixed(2));

document.writeln(c.toString()+"<br>");
document.writeln(d.toString()+"<br>");

document.writeln(d.toPrecision());
document.writeln(d.toPrecision(2));
document.writeln(d.toPrecision(3));
</script> </body> </html>
JS STRING OBJECT
String Object
• The String object let's you work with a series of characters and wraps
Javascript's string primitive data type with a number of helper methods.

• Because Javascript automatically converts between string primitives and String


objects, you can call any of the helper methods of the String object on a string
primitive.
• Syntax:
• Creating a String object:
• var val = new String(string);

Property Description
constructor Returns a reference to the String function that created the object.
length Returns the length of the string.
The prototype property allows you to add properties and methods
prototype
to an object.
<html>
<head>
<title>JavaScript String constructor property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
</script>
</body>
</html>
String Methods
Method Description
concat() Combines the text of two strings and returns a new string.
Used to find a match between a regular expression and a string, and
replace()
to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and a
search()
specified string.

split() Splits a String object into an array of strings by separating the string
into substrings.

substr() Returns the characters in a string beginning at the specified location


through the specified number of characters.
Returns the characters in a string between two indexes into the
substring()
string.

toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase


<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );

document.write("Concatenated String :" + str3);


</script>
</body>
</html>
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">

var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");

document.write(newstr );

</script>
</body>
</html>
<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script type="text/javascript">

var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";

if ( str.search(re) == -1 ){
document.write("Does not contain Apples" );
}else{
document.write("Contains Apples" );
}

</script>
</body>
</html>
<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">

var str = "Apples are round, and Apples are Juicy.";

document.write(str.toUpperCase( ));
</script>
</body>
</html>
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">

var str = "Apples are round, and Apples are Juicy.";

document.write(str.toString( ));
</script>
</body>
</html>
JAVASCRIPT MATH OBJECT
Math Object
• The math object provides you properties and methods for
mathematical constants and functions.

• Unlike the other global objects, Math is not a constructor.

• All 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:
• Here is the simple syntax to call properties and methods of Math.
• var pi_val = Math.PI;
• var sine_val = Math.sin(30);
Math Properties:

Property Description
Euler's constant and the base of natural logarithms, approximately
E
2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately
PI
3.14159.

Square root of 1/2; equivalently, 1 over the square root of 2,


SQRT1_2
approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
<html>
<head>
<title>JavaScript Math LN2 Property</title>
</head>
<body>
<script type="text/javascript">

document.write("Property Value is : " + Math.LN2);


document.write("Property Value is : " + Math.LN10);
document.write("Property Value is : " + Math.LOG2E);
document.write("Property Value is : " + Math.LOG10E);
document.write("Property Value is : " + Math.PI);
document.write("Property Value is : " + Math.SQRT2);
document.write("Property Value is : " + Math.SQRT1_4);

</script>
</body>
</html>
JavaScript Math Methods
Methods Description
abs() It returns the absolute value of the given number.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
ceil() It returns a smallest integer value, greater than or equal to
the given number.
cos() It returns the cosine of the given number.
floor() It returns largest integer value, lower than or equal to the
given number.
exp() It returns the exponential form of the given number.
round() It returns closest integer value of the given number.
sin() It returns the sine of the given number.
<html> <head> <title>JavaScript Math exp() Method</title> </head> <body>
<script type="text/javascript">
var value = Math.exp(1);
document.write("First Test Value : " + value );
var value = Math.exp(30);
document.write("<br />Second Test Value : " + value );
var value = Math.floor(30.9);
document.write("<br />Second Test Value : " + value );
var value = Math.floor(-2.9);
document.write("<br />Third Test Value : " + value );
var value = Math.max(10, 20, -1, 100);
document.write("First Test Value : " + value );
var value = Math.min(10, 20, -1, 100);
document.write("First Test Value : " + value );
var value = Math.log(10); document.write("First Test Value : " + value );
var value = Math.random( );
document.write("First Test Value : " + value );
var value = Math.round( 20.7 );
document.write("<br />Second Test Value : " + value );
var value = Math.round( 20.3 );
document.write("<br />Third Test Value : " + value );

</script> </body> </html>


JAVASCRIPT DATE OBJECT
Date Object
• The Date object is a datatype built into the JavaScript language.

• Date objects are created with the new Date( ) as shown below.

• Syntax:
• Here are different variant of Date() constructor:

• new Date( )
• new Date(milliseconds)
• new Date(datestring)
• new Date(year,month,date[,hour,minute,second,millisecond ])
Date Methods:
Method Description
Date() Returns today's date and time

Returns the day of the month for the specified date according to
getDate()
local time.

Returns the day of the week for the specified date according to local
getDay()
time.

getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
Returns the milliseconds in the specified date according to local
getMilliseconds()
time.
getMinutes() Returns the minutes in the specified date according to local time.
getMonth() Returns the month in the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.

getTime() Returns the numeric value of the specified date as the number of
milliseconds since January 1, 1970, 00:00:00 UTC.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getDate Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getDate() : " + dt.getDate() );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getDay Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995
23:15:00");
document.write("getDay() : " + dt.getDay() );
</script>
</body>
</html>
<html>
<head>
<title>JavaScript getFullYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getFullYear() : " + dt.getFullYear() );
document.write("getTime() : " + dt.getTime() );
document.write("getMilliseconds() : " + dt.getMilliseconds() );
document.write("getMinutes() : " + dt.getMinutes() );
document.write("getHours() : " + dt.getHours() );
</script>
</body>
</html>
JAVASCRIPT BOOLEAN OBJECT
The Boolean Object
• The Boolean object represents two values, either "true" or "false".
• If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the
empty string (""), the object has an initial value of false.
• Syntax:
• var val = new Boolean(value);

Boolean Properties
Property Description
constructor Returns a reference to the Boolean function that created the
object.
prototype The prototype property allows you to add properties and
methods to an object.
Constructor
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is:"+bool.constructor);
</script>
</body>
</html>
Prototype
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author)
{ this.title = title; this.author = author; }
</script> </head> <body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script> </body></html>
Boolean Methods
Method Description

toSource() Returns a string containing the source of the Boolean object;


you can use this string to create an equivalent object.

toString() Returns a string of either "true" or "false" depending upon the


value of the object.

valueOf() Returns the primitive value of the Boolean object.


toSource
<html>
<head>
<title>JavaScript toSource() Method</title>
</head>
<body>
<script type="text/javascript">
function book(title, publisher, price)
{
this.title = title;
this.publisher = publisher;
this.price = price; }
var newBook = new book("Perl","Leo Inc",200);
document.write(newBook.toSource());
</script>
</body>
</html>
toString
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.toString is : " + flag.toString() );
</script>
</body>
</html>
ValueOf
<html>
<head>
<title>JavaScript valueOf() Method</title> </head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() );
</script>
</body>
</html>
JAVASCRIPT REGEXP OBJECT
RegExp Object
• A regular expression is an object that describes a pattern of 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.
• Syntax
var pattern = new RegExp(pattern, attributes); or
var pattern = /pattern/attributes;
• 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 multiline matches,
respectively.
RegExp Object Contd..
• Brackets:
• Brackets ([]) have a special meaning when used in the context of
regular expressions. They are used to find a range of characters.

Expression Description

[...] Any one character between the brackets.

[^...] Any one character not between the brackets.

[0-9] It matches any decimal digit from 0 through 9.

[a-z] It matches any character from lowercase a through lowercase z.

[A-Z] It matches any character from uppercase A through uppercase Z.

[a-Z] It matches any character from lowercase a through uppercase Z.


• Quantifiers:
• The +, *, ?, and $ flags all follow a character sequence.

Expression Description
p+ It matches any string containing one or more p's.
p* It matches any string containing zero or more p's.
p? It matches any string containing at most one p.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
• Examples

Expression Description

[^a-zA-Z] It matches any string not containing any of the characters ranging
from a through z and A through Z.

p.p It matches any string containing p, followed by any character, in turn


followed by another p.

^.{2}$ It matches any string containing exactly two characters.

<b>(.*)</b> It matches any string enclosed within <b> and </b>.

p(hp)* It matches any string containing a p followed by zero or more


instances of the sequence hp.
• Modifiers:
• Several modifiers are available that can simplify the way you work
with regexps, like case sensitivity, searching in multiple lines, etc.

Modifier Description

i Perform case-insensitive matching.

m Specifies 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

g Performs a global match that is, find all matches rather than stopping
after the first match.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a case-insensitive search for "w3schools" in a


string.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script></body></html>
<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a multiline search for "is" at the beginning of each
line in a string.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "\nIs th\nis it?";
var patt1 = /^is/m;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script></body></html>
<html>
<body>

<p>Click the button to do a global search for "is" in a string.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>

</body>
</html>
RegExp Properties
Property Description

constructor Specifies the function that creates an object's prototype.

global Specifies if the "g" modifier is set.

ignoreCase Specifies if the "i" modifier is set.

lastIndex The index at which to start the next match.

multiline Specifies if the "m" modifier is set.

source The text of the pattern.


RegExp Methods
Method Description
exec() Executes a search for a match in its string parameter.
test() Tests for a match in its string parameter.
toSource() Returns an object literal representing the specified object;
you can use this value to create a new object.
toString() Returns a string representing the specified object.

You might also like