Popup Box in JavaScript

JavaScript supports three types of dialog boxes:

  • Alert box
  • Confirmation box
  • Pop up box

Alert Box

An alert dialog box is mostly used to give a warning message to the users especially for validation purposes when a use inputs some wrong data, we can use an alert box to display a warning message.

The drawback of Alert box is only one button “OK” is available to select and proceed.

Syntax

The window.alert() method can be written without the window prefix.

Example

Confirmation Box

A confirmation box is used to take user’s consent on any particular situation.

It displays two buttons: OK and Cancel. It can be called as the improvised version of an alert box.

When the user clicks on OK, the window method confirm() returns true. When user clicks on the Cancel button, confirm() returns false. 

Syntax

The window.confirm() method can also be written without the ‘window’ prefix.

Example

Prompt Box

The prompt box is useful when we want to pop-up a text box for getting user input.

Thus, it gives you provision to interact with user. The user needs to fill the field and click OK.

This dialog box is displayed using a method called prompt() which takes two parameters:

  • A label that you want to display in the text box
  • A default string needs to be displayed in the text box

Prompt box has two buttons: OK and Cancel.

If the user clicks the OK button, the window method prompt() will return the entered value from the text box.

If the user clicks the Cancel button, the window method returns null.

Syntax

The window.prompt() method can also be written without the ‘window’ prefix.

Example

Classes and Objects in JavaScript

A class is a set or category of things having some property or attribute in common i.e., car is a class having similar properties such as color, engine, gear, model number etc.

The “class” construct allows us to define prototype-based classes.

Syntax for declaring a class:

Objects

Objects are the instance of classes i.e., Car is a class and Jaguar is an object of the Car class

Let’s consider a variable named person:

var person = “Sherlock Holms”;

Objects are also like variables but they can contain many values; like

this code assigns many values (Sherlock, Holms, male) to a variable named person:

var person = {name:”Sherlock”, title:”Holms”, gender:”male”};

The values are written as name:value pairs.

Object Definition

var person = {FirstName:”Sherlock”, lastName:”Holms”, age:50};

Spaces and line breaks are not important. An object definition can span multiple lines:

Object Properties

The name:values pairs in JavaScript objects are called properties:

PropertyValue
firstNameJohn
lastNameDoe
age30

Accessing Object Properties

Object properties can be accessed in 2 ways:

  1. objectName.propertyName

or

2. objectName[“propertyName”]

Access Method 1

Output

Access Method 2

Regular Expression in JavaScript

What is a Regular Expression(RegEx)?

Regular expressions/sequence of characters are patterns used to match character combinations in strings.

A regEx can be a single character or a complicated pattern. Regular expressions can be used to perform text search and validation operations.

Special characters in regular expressions

CharacterMeaning
^It Matches the beginning of an input e.g., /^A/ does not match the ‘A’ in “an A”, but matches the ‘A’ in “An E”
$Matches the end of an input. If the multi line flag is set to true, it also matches immediately before a line break character e.g., /t$/ does not match the ‘t’ in “eater”, but matches it in “eat”
*Matches the preceding expression 0 or more times. Equivalent to {0,} e.g., /bo*/ matches ‘boooo’ in “A ghost booed” and ‘b’ in “A bird” but nothing in “A goat”
+Matches the preceding expression 1 or more times. Equivalent to {1,} e.g., /a+/ matches the ‘a’ in “candy” and all the a’s in “caaaandy”, but nothing in “cndy”
?Matches the preceding expression 0 or 1 time e,g., /e?le?/ matches the ‘er’ in “anger”, ‘le’ in “angle” and the ‘l’ in “also”
.The decimal point matches any single character except the newline character e.g., /.n/ matches ‘an’ and ‘on’ in “nay, an apple is on the tree”, but not ‘nay’.
x(?=y)Matches ‘x’ only if it is followed by ‘y’ e.g., /Jack(?=Spat)/ matches ‘Jack’ only whn it is followed by ‘Spat’. /Jack(?=Spat|Fost)/ matches ‘Jack’ only if it is followed by ‘Spat’ or ‘Fost’; However, neither ‘Spat’ nor ‘Fost’ is part of the match results.
x(?!y)Matches ‘x’ only if it is not followed by ‘y’ e.g., /\d+(?!\.)/ matches a number only when it is not followed by a decimal point e.g., the regular expression /\d+(?!\.)/.exec(“3.141”) matches ‘141’ but not ‘3.141’
x|yMatches ‘x’ or ‘y'(when there’s no match for ‘x’)
{n}Matches exactly n occurrences of the preceding expression where N must be a positive integer. For example, /a{2}/ doesn’t match the ‘a’ in “candy,” but matches all the a’s in “caandy,” and the first two a’s in “caandy”
{n,}Matches at least n occurrences of the preceding expression e.g., /a{2,}/ matches “aa”, “aaa” and “aaaa” but not “a”
[xyz]This pattern matches any one of the characters in the brackets
[^xyz]It matches anything that is not enclosed within the brackets. Everything that works in the normal character set also works e.g., [^abc] is the same as [^a-c]. This initially match ‘r’ in “brisket” and ‘h’ in “chop”
[\b]Matches a backspace
/dMatches a digit character i.e., equivalent to [0-9] e.g., /\d/ matches ‘3’ in “B3 is the number”
/DMatches a non-digit character i.e., equivalent to [^0-9] e.g., /\D/ matches ‘B’ in “B2 is the number”
\sMatches a white space character including space, tab, form feed, line feed etc e.g., /\s\w*/ matches ‘ bar’ in “tool bar”
\SMatches a character other than white space e.g., /\S*/ matches ‘foo’ in “foo bar”
\tMatches a tab
\wMatches any alphanumeric character including underscore e.g., /\w/ matches ‘a’ in “ant,” ‘5’ in “$528,” and ‘2’ in “2D”
\WMatches any non-word character e.g., /\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “70%”
\nWhere n is a positive integer, a back reference to the last substring matching the n characters in the regular expression
\xhhMatches two hexadecimal digits
\uhhhMatches four hexadecimal digits

Methods that uses regular expressions

MethodDescription
exec()It is a RegExp method that executes a search for a match in a string. It returns an array of information or null for a mismatch
test()A RegExp method that tests for a match in a string. It returns true or false
match()A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch
search()A String method that tests for a match in a string. It returns the index of the match or -1 if the search fails
replace()A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring
split()A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

Example

First see to match the part of a string using match()

Run

Output

ball,ball,ball,ball

To validate name that should contain only letters with minimum 3 character and maximum 15 characters.

The regular expression will be

/^[a-zA-Z]+$/

it will check one or more occurrence of a-z or A-Z

to limit no of characters we include character range there.

check for range between 3 to 15

/^[a-zA-Z]{3,15}$/

Run

to validate full name that my contain spaces above regular expression can be modified as

/^[a-zA-Z ]{3,15}$/

Program to check url and mail validity using regular expression

/^[0-9]+$/

validate number between zero to nine with minimum one digit

/^[0-9]{5,10}$/

accept digits between zero to 9 with range or 5 to 10 digits

one space is added after character range.

To accept characters and all digits we can use following

/^[a-zA-Z0-9]+$/

/^[a-zA-Z0-9]{5,10}$/

above regular expression will access alphanumeric in range of 5 to 10

to validate mail id

/^\w+([\.-]?\w+)[email protected]\w+([\.:]?\w+)+(\.[a-zA-Z0-9]{2,3})+$/

Run

to validate url we can use

/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&’\(\)\*\+,;=.]+$/

Run

Switch Statement in JavaScript

The switch statement performs different actions based on different condition.

It can be called as the replacement of multiple nested if-else statements.

The JavaScript Switch Statement

  • The switch statement is used to select one of many code blocks to be executed.
  • Switch case is useful for menu based application.

Syntax

How Switch Statement works?

  • At first, the switch expression is evaluated once.
  • The value of the expression is compared with each of the case.
  • If there is a match, the associated block of code is executed i.e., only one case will be executed.
  • If break is not written after each of the code blocks, all the cases are executed after execution of the matched case.
  • The default portion is executed only when the user inputs a wrong value(other than the case values).

The getDay() method returns the weekday as a number within the range 0-6.
(Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6)

Example

Loop Control Statement in JavaScript

The Break Statement

  • The break statement can be used to jump out of a loop even when the condition is true.
  • The break statement breaks the loop and continues executing all the code after the loop(if any):

OUTPUT

This time though, we want to stop execution of the loop when i become 3. To do so, we are inserting another conditional checking i, and if the test passes, we will break execution of the loop:

OUTPUT

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

OUTPUT