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

Regular Expressions in JavaScript

css chapter 4 diploma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Regular Expressions in JavaScript

css chapter 4 diploma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Regular Expressions in JavaScript: A Comprehensive Guide

Introduction to Regular Expressions (Regex)

A regular expression, commonly known as regex, is a powerful tool used to match patterns within text. In
JavaScript, regex is used for searching, matching, and manipulating strings. Regex can validate inputs,
locate substrings, extract useful data, and replace characters—all essential for web development.

A regular expression is created using a sequence of characters, where each character (or symbol) plays a
specific role in the search pattern.

In JavaScript, regex can be created in two main ways:

1. Using regex literal: The pattern is written between slashes /.../.

javascript
Copy code
let regex = /abc/;

2. Using the RegExp() constructor:

javascript
Copy code
let regex = new RegExp("abc");

This guide will cover every aspect of regex in JavaScript, from basic concepts to advanced topics. Each
concept will be followed by implementation examples written within HTML.

1. Regex Syntax and Flags

 Basic Regex Syntax: A regex pattern is typically enclosed between slashes (/pattern/). For example,
/hello/ matches the word "hello" in a string.
 Flags: Regex flags modify the behavior of a regular expression. Some common flags are:
o g (global): Searches for all matches within a string.
o i (case-insensitive): Makes the search case-insensitive.
o m (multi-line): Allows the search across multiple lines.

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
// Using different flags with regex
let regex = /hello/i; // Case-insensitive
let str = "Hello World!";
document.write(regex.test(str)); // Output: true
</script>
</body>
</html>

Explanation:
 The flag i makes the pattern case-insensitive, so it matches both "Hello" and "hello".

2. Methods for Using Regex in JavaScript

JavaScript provides multiple methods to work with regex:

2.1 test() Method

The test() method tests if a pattern is present in a string. It returns true if a match is found and false
otherwise.

Syntax:

javascript
Copy code
regex.test(string);

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /world/;
let str = "Hello world!";
document.write(regex.test(str)); // Output: true
</script>
</body>
</html>

Explanation:

 The test() method checks whether the word "world" is present in the string "Hello world!". It
returns true as "world" is indeed present.

2.2 exec() Method

The exec() method searches for a match in a string and returns an array of the matched result or null if no
match is found.

Syntax:

javascript
Copy code
regex.exec(string);

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /hello/i;
let str = "Hello World!";
let result = regex.exec(str);
document.write(result); // Output: hello
</script>
</body>
</html>

Explanation:

 The exec() method returns an array containing the match ("hello") regardless of the case due to the i
flag.

2.3 String Methods with Regex

 match(): Returns an array containing all matches or null.

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let str = "The quick brown fox jumps over the lazy dog.";
let result = str.match(/quick/);
document.write(result); // Output: quick
</script>
</body>
</html>

 replace(): Replaces matches with a specified replacement.

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let str = "Hello World!";
let result = str.replace(/hello/i, "Hi");
document.write(result); // Output: Hi World!
</script>
</body>
</html>

3. Character Sets and Ranges

Character sets allow you to define a group of characters you want to match.

3.1 Character Set ([])

 Definition: Character sets allow matching any one of the characters inside the brackets.
 Syntax: [abc] matches either 'a', 'b', or 'c'.

Example:
html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /[aeiou]/; // Matches any vowel
let str = "The quick brown fox.";
let result = str.match(regex);
document.write(result); // Output: e
</script>
</body>
</html>

Explanation:

 The regex /[aeiou]/ searches for the first vowel and matches "e".

3.2 Ranges

 Definition: Ranges are used to specify a range of characters.


 Syntax: [a-z] matches any lowercase letter.

Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /[a-z]/g; // Matches all lowercase letters
let str = "123abcXYZ";
let result = str.match(regex);
document.write(result); // Output: a,b,c
</script>
</body>
</html>

Explanation:

 The regex /[a-z]/g matches all lowercase letters in the given string.

4. Metacharacters

Metacharacters are symbols with special meanings in regex.

4.1 Dot (.)

 Definition: Matches any character except newline.


 Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /h.llo/;
let str = "hello, hillo";
let result = str.match(regex);
document.write(result); // Output: hello
</script>
</body>
</html>

4.2 \d (Digit)

 Definition: Matches any digit (0-9).


 Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /\d/g;
let str = "Phone: 123-456-7890";
let result = str.match(regex);
document.write(result); // Output: 1,2,3,4,5,6,7,8,9,0
</script>
</body>
</html>

4.3 \w (Word Character)

 Definition: Matches any letter, digit, or underscore (_).


 Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /\w/g;
let str = "Hello_123";
let result = str.match(regex);
document.write(result); // Output: H,e,l,l,o,_,1,2,3
</script>
</body>
</html>

5. Quantifiers

Quantifiers specify how many times a character or group should be present in the text.

5.1 Asterisk (*): Zero or more times

 Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /ho*/;
let str = "hooooly!";
let result = str.match(regex);
document.write(result); // Output: hooool
</script>
</body>
</html>

5.2 Plus (+): One or more times

 Example:

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /ho+/;
let str = "hooooly!";
let result = str.match(regex);
document.write(result); // Output: hooool
</script>
</body>
</html>

6. Grouping and Alternation

 Grouping (()): Groups multiple characters together and remembers them.


 Alternation (|): Acts as an OR operator.

Example (Grouping and Alternation):

html
Copy code
<!DOCTYPE html>
<html>
<body>
<script>
let regex = /(ab)+/; // Matches 'ab' one or more times
let str = "abababc";
let result = str.match(regex);
document.write(result); // Output: abab
</script>
</body>
</html>

7. Anchors

Anchors are used to specify positions in a string.

7.1 Caret (^)

Matches the beginning of a string.

Example:

html
Copy code
<script>
let regex = /^Hello/; // Checks if the string starts with 'Hello'
let str = "Hello World!";
let result = regex.test(str);
document.write(result); // Output: true
</script>

7.2 Dollar Sign ($)

Matches the end of a string.

Example:

html
Copy code
<script>
let regex = /World!$/; // Checks if the string ends with 'World!'
let str = "Hello World!";
let result = regex.test(str);
document.write(result); // Output: true
</script>

8. Lookaheads and Lookbehinds

Lookaheads and lookbehinds allow you to assert conditions without consuming characters.

**8.1 Positive Lookahead (`(?=...)

You might also like