Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Lecture 15 Java Script Part 2

Uploaded by

kananiparth04
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lecture 15 Java Script Part 2

Uploaded by

kananiparth04
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Java Script

Module 2
Content
• Statements
• Syntax
• Function
• Objects
JavaScript Statements • A computer program is a list of
<!DOCTYPE html> "instructions" to be "executed" by a
<html>
<body> computer.

<h2>JavaScript Statements</h2> • In a programming language, these


<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be programming instructions are called
executed by a computer.</p>
statements.
<p id="demo"></p>
• A JavaScript program is a list of
<script>
let x, y, z; // Statement 1 programming statements.
x = 5; // Statement 2
y = 6; // Statement 3 • In HTML, JavaScript programs are
z = x + y; // Statement 4
executed by the web browser.
document.getElementById("demo").innerHTML = "The value of z is " + z +
"."; • JavaScript statements are composed of:
</script>
• Values
</body>
</html> • Operators

• Expressions

• Keywords

• Comments.
JavaScript Statements • Most JavaScript programs contain many
<!DOCTYPE html> JavaScript statements.
<html>
<body>
• The statements are executed, one by one, in
<h2>JavaScript Statements</h2> the same order as they are written.
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be
executed by a computer.</p>
• JavaScript programs (and JavaScript
statements) are often called JavaScript code
<p id="demo"></p>

<script> Semicolons:
let x, y, z; // Statement 1
x = 5; // Statement 2 • Semicolons separate JavaScript statements.
y = 6; // Statement 3
z = x + y; // Statement 4 • Add a semicolon at the end of each executable
document.getElementById("demo").innerHTML = "The value of z is " + z + statement
".";
</script> • When separated by semicolons, multiple
</body> statements on one line are allowed
</html>
• Ending statements with semicolon is not
required, but highly recommended
JavaScript Statements
<!DOCTYPE html>
JavaScript White Space
<html>
<body> • JavaScript ignores multiple spaces.

<h2>JavaScript Statements</h2> • We can add white space to your script to


<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be make it more readable
executed by a computer.</p>

<p id="demo"></p>
• A good practice is to put spaces around
operators ( = + - * / )
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2 JavaScript Line Length and Line Breaks
y = 6; // Statement 3
z = x + y; // Statement 4 • For best readability, programmers often
document.getElementById("demo").innerHTML = "The value of z is " + z + like to avoid code lines longer than 80
".";
</script> characters.

</body> • If a JavaScript statement does not fit on


</html>
one line, the best place to break it is
after an operator:
JavaScript Statements
<!DOCTYPE html> JavaScript Code Blocks
<html>
<body> • JavaScript statements can be grouped
<h2>JavaScript Statements</h2> together in code blocks, inside curly

<p>JavaScript code blocks are written between { and }</p>


brackets {...}.

<button type="button" onclick="myFunction()">Click • The purpose of code blocks is to


Me!</button>
define statements to be executed
<p id="demo1"></p> together.
<p id="demo2"></p>
• One place you will find statements
<script>
function myFunction() { grouped together in blocks, is in
document.getElementById("demo1").innerHTML = "Hello!";
document.getElementById("demo2").innerHTML = "How are JavaScript functions
you?";
}
</script>

</body>
</html>
JavaScript Statements
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click


Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello!";
document.getElementById("demo2").innerHTML = "How are
you?";
}
</script>

</body>
</html>
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Some of the keywords:


Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
JavaScript
Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed

JavaScript Values
The JavaScript syntax defines two types of values:
• Fixed values – Literals
• Variable values – Variables

JavaScript Variables
JavaScript Literals
• In a programming language, variables are used
The two most important syntax rules for fixed values are:
to store data values.
1. Numbers are written with or without decimals
• JavaScript uses the keywords var, let and const to
2. Strings are text, written within double or single
declare variables.
quotes
• An equal sign is used to assign values to
variables.
JavaScript
Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed

JavaScript Operators
• Arithmetic operators: + , - , * , / , ** , % , ++ , --
• Assignment operator: = , += , -= , *= , /= , %= , **=
• String operator: + , +=
• Comparison Operator: == (Equal to) , === (Equal Value and Equal Type), != , < , > , <= , >= , ?
• Logical Operator: && , || , !
• Type Operators: typeof, instanceof
• Bitwise Operators: & , | , ~ , ^ , << , >>
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed

JavaScript Operators
Arithmetic operators: Addition ( + ), Subtraction( - ), Multiplication( * ), Division ( / )
Assignment operator: ( = )

JavaScript Expressions

• An expression is a combination of values, variables, and operators, which computes to a value.

• The computation is called an evaluation.


• For example, 5 * 10 evaluates to 50

• Expressions can also contain variable values

• The values can be of various types, such as numbers and strings.


• For example, "John" + " " + "Doe", evaluates to "John Doe"
JavaScript
Syntax
JavaScript Comments

• Not all JavaScript statements are "executed".

• Code after double slashes // or between /* and */ is treated as a comment.

• Comments are ignored, and will not be executed


JavaScript
Syntax
JavaScript Identifiers
Rules:
• Identifiers are names.

• In JavaScript, identifiers are used In JavaScript, the first character must be a letter, or an
underscore (_), or a dollar sign ($).
to name variables (and
keywords, and functions, and Subsequent characters may be letters, digits, underscores, or
labels). dollar signs.

• The rules for legal names are


much the same in most All JavaScript identifiers are case sensitive

programming languages.
JavaScript programmers tend to use camel case that starts
with a lowercase letter:
JavaScript function name(parameter1, parameter2, parameter3)
Functions {
// code to be executed
}
• It is a block of code designed to
It is defined with the function keyword, followed by a name, followed by
perform a particular task parentheses ().

• It is executed when "something" Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).

invokes it (calls it)


The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
Syntax:
The code to be executed, by the function, is placed inside curly
brackets: { }

Inside the function, the arguments (the parameters) behave as


local variables.

Function parameters are listed inside the parentheses () in the


function definition.

Function arguments are the values received by the function when it is


invoked.
JavaScript Functions Function Invocation

The code inside the function will execute when


<!DOCTYPE html>
<html> "something" invokes (calls) the function:
<body>
• When an event occurs (when a user clicks a
<h2>JavaScript Functions</h2> button)

<p>This example calls a function which performs a • When it is invoked (called) from JavaScript code
calculation and returns the result:</p>
• Automatically (self invoked)
<p id="demo"></p>

<script>
var x = myFunction(4, 3); Function Return
document.getElementById("demo").innerHTML = x;
• When JavaScript reaches a return statement, the
function myFunction(a, b) {
function will stop executing.
return a * b;
}
• If the function was invoked from a statement,
</script>
JavaScript will "return" to execute the code after
</body>
the invoking statement.
</html>
• Functions often compute a return value. The
return value is "returned" back to the "caller
JavaScript Functions
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a


calculation and returns the result:</p>

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

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>

</body>
</html>
JavaScript Functions Function Invocation
<!DOCTYPE html>
Accessing a function without () will return
<html>
<body> the function object instead of the function
<h2>JavaScript Functions</h2> result.

<p>Accessing a function without () will return the function


definition instead of the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>

</body>
</html>
JavaScript Objects
JavaScript Objects
Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color, and methods like start and stop
• All cars have the same properties, but the property values differ from car to car.
• All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
• Objects are variables but it contain many values.
• The values are written as name:value pairs (name and value separated by a colon).
• It is a common practice to declare objects with the const keyword.
• We can define (and create) a JavaScript object with an object literal
• Spaces and line breaks are not important.
• An object definition can span multiple lines
Object Definition on Single Line
JavaScript Objects
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

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

<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:


document.getElementById("demo").innerHTML = "The car type is " +
car.type;
</script>

</body>
</html>
JavaScript Objects Object Definition on Multiple Line
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

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

<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>
JavaScript Objects
Object Properties
The name:values pairs in JavaScript objects are called properties:

Property Property Value


firstName John
lastName Doe
age 50
eyeColor blue

You can access object properties in two ways:


objectName.propertyName OR objectName["propertyName"]
JavaScript Objects Accessing Property Value
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

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

<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>
JavaScript Object Methods

Objects
<!DOCTYPE html>
Objects can also have methods.
<html> Methods are actions that can be performed on objects.
<body>
Methods are stored in properties as function definitions.
<h2>JavaScript Objects</h2>
A method is a function stored as a property.
<p>An object method is a function definition, stored
as a property value.</p>

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

<script> Property Property Value


// Create an object:
const person = { firstName John
firstName: "John",
lastName: "Doe",
lastName Doe
id: 5566, age 50
fullName: function() {
return this.firstName + " " + this.lastName; eyeColor blue
}
}; fullName function()

// Display data from the object: {return this.firstName + " " + this.lastName;}
document.getElementById("demo").innerHTML =
person.fullName();
</script>

</body>
</html>
JavaScript
Objects
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored
as a property value.</p>

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

<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML =
person.fullName();
</script>

</body>
</html>
JavaScript
Objects
<!DOCTYPE html>
<html>
<body> Accessing Object Methods
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored We can access an object method with the following
as a property value.</p>
syntax:
<p id="demo"></p>
objectName.methodName()
<script>
// Create an object:
const person = { If you access a method without the () parentheses, it will
firstName: "John",
lastName: "Doe",
return the function definition
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML =
person.fullName;
</script>

</body>
</html>
JavaScript Date
JavaScript Date
• JavaScript Date Object lets us work with dates

• JavaScript will use the browser's time zone and display a date as a full text string

Fri Aug 27 2021 12:12:10 GMT+0530 (India Standard Time)

• Date objects are created with the new Date() constructor.

• There are 4 ways to create a new date object:

new Date( )

new Date(year, month, day, hours, minutes, seconds, milliseconds)

new Date(milliseconds)

new Date(date string)


JavaScript Date new Date( )

• It creates a new date object with the current


<!DOCTYPE html>
<html> date and time
<body>
• Date objects are static.
<h2>JavaScript new Date()</h2>
<p>Using new Date(), creates a new date object • The computer time is ticking, but date objects
with the current date and time:</p>
are not
<p id="demo"></p>
• Example
<script>
const d = new Date(); const d = new Date( );
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
JavaScript Date new Date(year, month, ...)

• It creates a new date object with a specified date and time.


<!DOCTYPE html>
• 7 numbers specify year, month, day, hour, minute, second,
<html>
and millisecond (in that order)
<body>
• Example

<h2>JavaScript new Date()</h2> const d = new Date(2018, 11, 24, 10, 33, 30, 0);
<p>Using new Date(), creates a new date object
• JavaScript counts months from 0 to 11:
with the current date and time:</p>
January = 0.

<p id="demo"></p> December = 11.

• Specifying a month higher than 11, will not result in an error


<script>
but add the overflow to the next year
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
Specifying: const d = new Date(2018, 15, 24, 10, 33,
document.getElementById("demo").innerHTML = d;
</script> 30);

Is the same as: const d = new Date(2019, 3, 24, 10, 33,


</body>
30);
</html>
• Specifying a day higher than max, will not result in an error
JavaScript Date
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript new Date()</h2>


<p>Using new Date(), creates a new date object
with the current date and time:</p>

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

<script>
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
JavaScript Date new Date(dateString)

<!DOCTYPE html> It creates a new date object from a date string


<html>
• Example
<body>

const d = new Date("October 13, 2014 11:13:00");


<h2>JavaScript new Date()</h2>
<p>A Date object can be created with a specified
date and time:</p>

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

<script>
const d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
JavaScript Date new Date(milliseconds)

<!DOCTYPE html>
• It creates a new date object as zero time plus milliseconds
<html> • Example
<body>
const d = new Date(0);
<h2>JavaScript new Date()</h2>
• JavaScript stores dates as number of milliseconds since
<p>A Date object can be created with a specified
January 01, 1970, 00:00:00 UTC (Universal Time
date and time:</p>
Coordinated).
<p id="demo"></p>
• Zero time is January 01, 1970 00:00:00 UTC.

<script> • One day (24 hours) is 86 400 000 milliseconds


const d = new Date(0);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
JavaScript Date
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript new Date()</h2>


<p>A Date object can be created with a specified
date and time:</p>

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

<script>
const d = new Date(0);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
Date Methods
JavaScript
• When a Date object is created, a number of methods allow you to operate on it.
Date
• Date methods allow you to get and set the year, month, day, hour, minute, second,

and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

• JavaScript will (by default) output dates in full text string format:

Fri Aug 27 2021 12:12:10 GMT+0530 (India Standard Time)

• d.toString( ) method: Convert date object into string

• d.toUTCString( ) method: converts a date to a UTC string (a date display standard)

• Format: Fri, 27 Aug 2021 07:16:54 GMT

• d.toDateString( ) method: converts a date to a more readable format

• Format: Fri Aug 27 2021

• How to use it?

const d = new Date();

document.getElementById("demo").innerHTML = d.toDateString();
Date Formats
JavaScript
There are generally 3 types of JavaScript date input formats:
Date

Type Example

ISO Date "2015-03-25" (The International Standard)

Short Date "03/25/2015"

Long Date "Mar 25 2015" or "25 Mar 2015“

• The ISO format follows a strict standard in JavaScript.

• The other formats are not so well defined and might be browser specific
JavaScript
Date
JavaScript ISO Dates

• ISO 8601 is the international standard for the representation of dates and times.

• The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format

• The computed date will be relative to your time zone.

Example (Complete date) const d = new Date("2015-03-25");

• ISO dates can be written without specifying the day (YYYY-MM):

Example const d = new Date("2015-03");

• ISO dates can be written without month and day (YYYY):

Example: const d = new Date("2015");

• ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):

Example const d = new Date("2015-03-25T12:00:00Z");

• Date and time is separated with a capital T.

• UTC time is defined with a capital letter Z.

• If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM

instead:
JavaScript Short Dates
JavaScript
• Short dates are written with an "MM/DD/YYYY" syntax like
Date
• Example: const d = new Date("03/25/2015");

• In some browsers, months or days with no leading zeroes may produce an error:

Example: const d = new Date("2015-3-25");

• The behavior of "YYYY/MM/DD" is undefined.

• Some browsers will try to guess the format. Some will return NaN.

Example: const d = new Date("2015/03/25");

• The behavior of "DD-MM-YYYY" is also undefined.

• Some browsers will try to guess the format. Some will return NaN.

Example: const d = new Date("25-03-2015");


JavaScript
JavaScript Long Dates
Date
• Long dates are most often written with a "MMM DD YYYY" syntax like this:

Example

const d = new Date("Mar 25 2015");

• Month and day can be in any order

• Month can be written in full (January), or abbreviated (Jan)

• Commas are ignored.

• Names are case insensitive


JavaScript Get Date Methods JavaScript
Method Description Date
getFullYear() Get the year as a four digit number (yyyy)

getMonth() Get the month as a number (0-11)

getDate() Get the day as a number (1-31)

getHours() Get the hour (0-23)

getMinutes() Get the minute (0-59)

getSeconds() Get the second (0-59)

getMilliseconds() Get the millisecond (0-999)

getTime() Get the time (milliseconds since January 1,

1970)

getDay() Get the weekday as a number (0-6)

Date.now() Get the time.


<!DOCTYPE html>
JavaScript
<html> Date
<body>

<h2>JavaScript getMonth()</h2>
<p>The getMonth() method returns the month as a number:</p>
<p>You can use an array to display the name of the month:</p>

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

<script>
const d = new Date();
const months =
["January","February","March","April","May","June","July","August","September","October","Novem
ber","December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
</script>

</body>
</html>
JavaScript
JavaScript Set Date Methods
Date
Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)


<!DOCTYPE html>
<html>
JavaScript Date
<body>

<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method can optionally set month and day.</p>
<p>Please note that month counts from 0. December is month
11:</p>

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

<script>
const d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>
Comparing Dates
JavaScript Date
Dates can be easily compared
<!DOCTYPE html>
<html>
<body>

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

<script>
let text;
const today = new Date();
const someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {


text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
JavaScript Regular
Expression
JavaScript Regular
Expression
• A regular expression is a sequence of characters that forms a search pattern.

• When you search for data in a text, you can use this search pattern to describe what you are

searching for.

• A regular expression can be a single character, or a more complicated pattern.

• Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

/pattern/modifiers;

Example

/w3schools/i;

• /w3schools/i is a regular expression.

• w3schools is a pattern (to be used in a search).

• i is a modifier (modifies the search to be case-insensitive).


JavaScript Regular
Expression

Using String Methods

• In JavaScript, regular expressions are often used with the two string methods: search()

and replace().

• The search() method: It uses an expression to search for a match, and returns the

position of the match.

• The replace() method: It returns a modified string where the pattern is replaced.
JavaScript Regular
Expression
String search() With a String

• The search() method searches a string for a specified value and returns the position of the match:

Example: Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";

let n = text.search("W3Schools");

The result in n will be: 6

String search() With a Regular Expression

Example: Use a regular expression to do a case-insensitive search for "w3schools" in a string

let text = "Visit W3Schools";

let n = text.search(/w3schools/i);

The result in n will be: 6


JavaScript Regular
Expression
String replace() With a String

• The replace() method replaces a specified value with another value in a string

• Example:

let text = "Visit Microsoft!";

let result = text.replace("Microsoft", "W3Schools");

The result in result will be: visit W3Schools

String replace() With a Regular Expression

Example: Use a regular expression to do a case-insensitive search for "w3schools" in a string

let text = "Visit Microsoft!";

let res = text.replace(/microsoft/i, "W3Schools");

The result in res will be: W3Schools


JavaScript Regular
Expression

• Regular expression arguments (instead of string arguments) can be used in the methods

• Regular expressions can make your search much more powerful (case insensitive for example)

Regular Expression Modifiers

• Modifiers can be used to perform case-insensitive more global searches:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first match)

m Perform multiline matching


Regular Expression Patterns
JavaScript Regular
• Brackets are used to find a range of characters: Expression

Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets

(x|y) Find any of the alternatives separated with |

• Metacharacters are characters with a spec

Metacharacter Description

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\ \

uxxxx Find the Unicode character specified by the hexadecimal number xxxx
JavaScript Regular
Expression
Regular Expression Patterns

Quantifiers Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n


Using the RegExp Object
JavaScript Regular
Expression
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using test()

• The test() method is a RegExp expression method.

• It searches a string for a pattern, and returns true or false, depending on the result.

• The following example searches a string for the character "e":

Example:

const pattern = /e/;

pattern.test("The best things in life are free!");

Since there is an "e“ in the string, the output of the code above will be: true

• You don't have to put the regular expression in a variable first. The two lines above can be shortened to

one:
JavaScript Regular
Expression
Using the RegExp Object

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using exec()

• The exec() method is a RegExp expression method.

• It searches a string for a specified pattern, and returns the found text as an object.

• If no match is found, it returns an empty (null) object.

• The following example searches a string for the character "e":

Example

/e/.exec("The best things in life are free!");

You might also like