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

The RegExp Object javascript

Uploaded by

yogitas804
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

The RegExp Object javascript

Uploaded by

yogitas804
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

The RegExp Object

A regular expression is a pattern of characters.

The pattern is used for searching and replacing characters in strings.

The RegExp Object is a regular expression with


added Properties and Methods.

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The /i Modifier</h2>

<p>A case-insensitive search for "cdac computer center" in a string:</p>

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

<script>

let text = "cdac computer center";

let pattern = /computer/i;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>

Modifiers
Modifiers define how to perform the search:

Modifier Description
/g Perform a global match (find all)

/i Perform case-insensitive matching

/m Perform multiline matching

Brackets
Brackets are used to find a range of characters:

Bracket Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-
digit)

(x|y) Find any of the alternatives specified

Metacharacters
Metacharacters are characters with a special meaning:

Character Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like


this: \bHI, end like this: HI\b
\B Find a match, but not at the beginning/end of a word

\0 Find a NULL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\udddd Find the Unicode character specified by a hexadecimal


number dddd

Quantifiers
Quantifier 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

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least


X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string n

RegExp Object Properties


Property Description

constructor Returns the function that created the RegExp object's


prototype

global Checks whether the "g" modifier is set

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern

RegExp Object Methods


Method Description

compile() Deprecated in version 1.5. Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The test() method returns true if it finds a match, otherwise false.</p>

<p>Search a string for the character "e":</p>

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

<script>

let text = "The best things in life are free";

let pattern = /e/;

let result = pattern.test(text);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript RegExp</h2>

<p>The exec() method tests for a match in a string:</p>

<p>Search a string for the character "e":</p>

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

<script>

let text = "The best things in life are free";

let result = /e/.exec(text);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>toString() returns the string value of a RegExp object:</p>

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

<script>

let pattern = new RegExp("Hello World", "g");

let text = pattern.toString();

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The g Modifier</h2>

<p>A global search for "is" in a string:</p>

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

<script>

let text = "Is this all there is?";

let pattern = /is/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The m Modifier</h2>

<p>Do a multiline search for "is" at the beginning of each line in a string:</p>

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

<script>

let text = `Is this

all there

is`

let pattern = /^is/m;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>Using [ ] to find a range of characters</h2>

<p>A global search for characters that are not "h":</p>

<!DOCTYPE html>

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

<script>

let text = "Is this all there is?";

let pattern = /[^h]/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>Using [ ] to find a range of characters</h2>

<p>A global search for the numbers 1 to 4:</p>

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

<script>

let text = "123456789";

let pattern = /[1-4]/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>Using [ ] to find a range of characters</h2>

<p>A global search for numbers that are NOT from 1 to 4:</p>

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

<script>

let text = "123456789";

let pattern = /[^1-4]/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>Using | as OR</h2>

<p>A global search for the red OR green:</p>

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

<script>

let text = "re, green, red, green, gren, gr, blue, yellow";

let pattern = /(red|green)/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The . Metacharacter</h2>

<p>A global search for any character between h and t:</p>

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

<script>

let text = "That's hot!";

let pattern = /h.t/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The w Metacharacter</h2>

<p>A global search for word characters:</p>

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

<script>

let text = "Give 100%!";

let pattern = /\w/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The W Metacharacter</h2>

<p>A global search for non-word characters:</p>

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

<script>

let text = "Give 100%!";

let pattern = /\W/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The + Quantifier</h2>

<p>A global search for at least one "o" in a string:</p>

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

<script>

let text = "Hellooo World! Hello W3Schools!";

let pattern = /o+/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The * Quantifier</h2>

<p>A global search for an "l", followed by zero or more "o" characters:</p>

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

<script>

let text = "Hellooo World! Hello W3Schools!";

let pattern = /lo*/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The ? Quantifier</h2>

<p>A global search for a "1", followed by zero or one "0" characters:</p>

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

<script>

let text = "1, 100 or 1000?";

let pattern = /10?/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The {} Quantifier</h2>

<p>A global search for sequence of four digits:</p>

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

<script>

let text = "100, 1000 or 10000?";

let pattern = /\d{4}/g;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Regular Expression</h1>

<h2>The ?= Quantifier</h2>

<p>Search for "is" followed by " all":</p>

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

<script>

let text = "Is this all there is";

let pattern = /is(?= all)/;

let result = text.match(pattern);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The constructor property returns the function that created the RegExp prototype:</p>

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

<script>

let pattern = /Hello World/g;

let text = pattern.constructor;

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The global property returns true if the "g" modifier is set, otherwise false:</p>

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

<script>

let pattern = /W3S/g;

let result = pattern.global;

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The ignoreCase property returns true if the "i" modifier is set, otherwise false:</p>

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

<script>

let text = "Visit W3Schools!";

let pattern = /W3S/i;

let result = pattern.ignoreCase;

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The lastIndex property specifies the index at which to start the next match:</p>

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

<script>

let text = "The rain in Spain stays mainly in the plain";

let pattern = /ain/g;

let result = "";

while (pattern.test(text)==true) {

result += "Found at position " + pattern.lastIndex + "<br>";

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The multiline property returns true if the "m" modifier is set, otherwise false:</p>

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

<script>

let text = "Visit W3Schools!";

let pattern = /W3S/gi;

let result = pattern.multiline;

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>The source property returns the text of a RegExp pattern:</p>

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

<script>

let text = "Visit W3Schools";

let pattern = /W3S/g;

let result = pattern.source;

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
JavaScript Form Validation
HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:

JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

<!DOCTYPE html>

<html>

<head>

<script>

function validateForm() {

let x = document.forms["myForm"]["fname"].value;

if (x == "") {

alert("Name must be filled out");

return false;

</script>

</head>

<body>

<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"
method="post">

Name: <input type="text" name="fname">

<input type="submit" value="Submit">

</form>

</body>

</html>

JavaScript Can Validate Numeric


Input
JavaScript is often used to validate numeric input:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Validation</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

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

<script>

function myFunction() {
// Get the value of the input field with id="numb"

let x = document.getElementById("numb").value;

// If x is Not a Number or less than one or greater than 10

let text;

if (isNaN(x) || x < 1 || x > 10) {

text = "Input not valid";

} else {

text = "Input OK";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

Automatic HTML Form Validation


HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form
from being submitted:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Validation</h2>

<form action="/action_page.php" method="post">

<input type="text" name="fname" required>

<input type="submit" value="Submit">


</form>

<p>If you click submit, without filling out the text field,

your browser will display an error message.</p>

</body>

</html>

Data Validation
Data validation is the process of ensuring that user input is clean, correct,
and useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been
sent to the server.

Client side validation is performed by a web browser, before input is sent


to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint
validation.

HTML constraint validation is based on:

 Constraint validation HTML Input Attributes


 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input


Attributes
Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element


The value Attribute
The input value attribute specifies an initial value for an input field:

Example
Input fields with initial (default) values:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The readonly Attribute


The input readonly attribute specifies that an input field is read-only.

A read-only input field cannot be modified (however, a user can tab to it,
highlight it, and copy the text from it).

The value of a read-only input field will be sent when submitting the form!

Example
A read-only input field:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" readonl
y><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The disabled Attribute


The input disabled attribute specifies that an input field should be disabled.
A disabled input field is unusable and un-clickable.

The value of a disabled input field will not be sent when submitting the form!

Example
A disabled input field:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" disable
d><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The size Attribute


The input size attribute specifies the visible width, in characters, of an input
field.

The default value for size is 20.

Note: The size attribute works with the following input types: text, search,
tel, url, email, and password.

Example
Set a width for an input field:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" size="4">
</form>

The maxlength Attribute


The input maxlength attribute specifies the maximum number of characters
allowed in an input field.

Note: When a maxlength is set, the input field will not accept more than the
specified number of characters. However, this attribute does not provide any
feedback. So, if you want to alert the user, you must write JavaScript code.

Example
Set a maximum length for an input field:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" maxlength="4" size="4">
</form>

The min and max Attributes


The input min and max attributes specify the minimum and maximum values
for an input field.

The min and max attributes work with the following input types: number,
range, date, datetime-local, month, time and week.

Tip: Use the max and min attributes together to create a range of legal
values.

Example
Set a max date, a min date, and a range of legal values:

<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-
31"><br><br>

<label for="datemin">Enter a date after 2000-01-01:</label>


<input type="date" id="datemin" name="datemin" min="2000-01-
02"><br><br>

<label for="quantity">Quantity (between 1 and 5):</label>


<input type="number" id="quantity" name="quantity" min="1" max=
"5">
</form>

The multiple Attribute


The input multiple attribute specifies that the user is allowed to enter more
than one value in an input field.

The multiple attribute works with the following input types: email, and file.

Example
A file upload field that accepts multiple values:

<form>
<label for="files">Select files:</label>
<input type="file" id="files" name="files" multiple>
</form>

The pattern Attribute


The input pattern attribute specifies a regular expression that the input field's
value is checked against, when the form is submitted.

The pattern attribute works with the following input types: text, date, search,
url, tel, email, and password.

Tip: Use the global title attribute to describe the pattern to help the user.

Tip: Learn more about regular expressions in our JavaScript tutorial.

Example
An input field that can contain only three letters (no numbers or special
characters):

<form>
<label for="country_code">Country code:</label>
<input type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}" title="Three letter country code">
</form>

The placeholder Attribute


The input placeholder attribute specifies a short hint that describes the
expected value of an input field (a sample value or a short description of the
expected format).

The short hint is displayed in the input field before the user enters a value.

The placeholder attribute works with the following input types: text, search,
url, number, tel, email, and password.

Example
An input field with a placeholder text:

<form>
<label for="phone">Enter a phone number:</label>
<input type="tel" id="phone" name="phone"
placeholder="123-45-678"
pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
</form>

The required Attribute


The input required attribute specifies that an input field must be filled out
before submitting the form.

The required attribute works with the following input types: text, search, url,
tel, email, password, date pickers, number, checkbox, radio, and file.

Example
A required input field:
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</form>

The step Attribute


The input step attribute specifies the legal number intervals for an input field.

Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.

Tip: This attribute can be used together with the max and min attributes to
create a range of legal values.

The step attribute works with the following input types: number, range, date,
datetime-local, month, time and week.

Example
An input field with a specified legal number intervals:

<form>
<label for="points">Points:</label>
<input type="number" id="points" name="points" step="3">
</form>

The autofocus Attribute


The input autofocus attribute specifies that an input field should automatically
get focus when the page loads.

Example
Let the "First name" input field automatically get focus when the page loads:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" autofocus><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

The height and width Attributes


The input height and width attributes specify the height and width of
an <input type="image"> element.

Tip: Always specify both the height and width attributes for images. If height
and width are set, the space required for the image is reserved when the
page is loaded. Without these attributes, the browser does not know the size
of the image, and cannot reserve the appropriate space to it. The effect will
be that the page layout will change during loading (while the images load).

Example
Define an image as the submit button, with height and width attributes:

<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48
" height="48">
</form>

The list Attribute


The input list attribute refers to a <datalist> element that contains pre-
defined options for an <input> element.

Example
An <input> element with pre-defined values in a <datalist>:
<form>
<input list="browsers">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>

The autocomplete Attribute


The input autocomplete attribute specifies whether a form or an input field
should have autocomplete on or off.

Autocomplete allows the browser to predict the value. When a user starts to
type in a field, the browser should display options to fill in the field, based on
earlier typed values.

The autocomplete attribute works with <form> and the following <input> types:
text, search, url, tel, email, password, datepickers, range, and color.

Example
An HTML form with autocomplete on, and off for one input field:

<form action="/action_page.php" autocomplete="on">


<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" autocomplete="off">
<br><br>
<input type="submit" value="Submit">
</form>

You might also like