JavaScript Regular Expressions and Type Conversion

Posted by Anonymous and classified in Computers

Written on in English with a size of 7.08 KB

Introduction to Regular Expressions

A Regular Expression (often abbreviated as RegExp or regex) is a sequence of characters that forms a search pattern. This pattern can be used for text search, text replace, and data validation operations.

In JavaScript, regular expressions are objects. You can create a RegExp object in two ways:

  • Using a RegExp Literal (Recommended): The pattern is enclosed between forward slashes.
    const regex = /pattern/modifiers;
  • Using the RegExp Constructor:
    const regex = new RegExp('pattern', 'modifiers');
    

RegExp Modifiers and Flags

Modifiers change how a regular expression searches text. They are appended to the end of the regex literal (e.g., /abc/g) or passed as the second argument to the constructor.

ModifierDescription
iCase-insensitive matching (ignores upper/lower case differences).
gGlobal matching (finds all matches rather than stopping after the first one).
mMultiline matching (affects the behavior of anchors ^ and $).
sDotAll matching (allows the dot . to match newline characters).

Regular Expression Patterns

Patterns define what you are searching for. They are built using literal characters, brackets, metacharacters, and quantifiers.

Brackets and Character Sets

Brackets are used to find a range or group of characters.

  • [abc]: Finds any character inside the brackets (a, b, or c).
  • [^abc]: Finds any character not inside the brackets.
  • [0-9]: Finds any digit from 0 to 9.

Common Metacharacters

Metacharacters are characters with special pre-defined meanings.

  • .: Matches any single character except a newline.
  • \d: Matches any digit (equivalent to [0-9]).
  • \w: Matches any word character (alphanumeric and underscore).
  • \s: Matches any whitespace character (space, tab, newline).
  • \b: Matches a word boundary (the beginning or end of a word).

Quantifiers for Matching

Quantifiers define the quantities of characters to match.

  • 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 occurrence of n.
  • n{X}: Matches a sequence of exactly X ns.

JavaScript RegExp Methods

The JavaScript RegExp object itself provides two primary built-in methods:

The test() Method

Tests for a match in a string. It returns true if it finds a match, and false if it doesn't.

const pattern = /hello/i;
console.log(pattern.test("Hello World")); // Output: true

The exec() Method

Searches a string for a specified pattern and returns a detailed array containing the matched text, index, and input string. If no match is found, it returns null.

const pattern = /world/i;
const result = pattern.exec("Hello World!");
console.log(result[0]);    // Output: "World" (the matched text)
console.log(result.index); // Output: 6 (the position of the match)

String Methods Using Regular Expressions

Several built-in String methods accept regular expressions as arguments to perform advanced text manipulation.

The match() Method

Returns an array containing all of the matches found in the string. Requires the /g flag to get all matches.

const str = "The rain in SPAIN stays mainly in the plain";
console.log(str.match(/ain/gi)); // Output: ['ain', 'AIN', 'ain', 'ain']

The replace() Method

Searches for a specified pattern and replaces it with a new string.

const str = "Visit Microsoft!";
const newStr = str.replace(/microsoft/i, "Google");
console.log(newStr); // Output: "Visit Google!"

The search() Method

Searches a string for a specified value and returns the index position of the match. Returns -1 if no match is found.

const str = "Mr. Blue has a blue house";
console.log(str.search(/blue/i)); // Output: 4

The split() Method

Breaks a string into an array of substrings using a regular expression to define the separator.

const list = "apple, banana; orange grass";
console.log(list.split(/[,;\s]+/)); // Output: ['apple', 'banana', 'orange', 'grass']

Type Conversion in JavaScript

Type conversion is the process of converting a value from one data type to another. In JavaScript, this happens in two ways: Implicit (Coercion) and Explicit.

Implicit Type Conversion and Coercion

JavaScript is a loosely typed language, meaning it will automatically convert types behind the scenes when it thinks it makes sense contextually.

// To String: Number + String = String
let res1 = '5' + 2;     // "52"

// To Number: Math operations with strings (except +)
let res2 = '5' - 2;     // 3
let res3 = '5' * '2';   // 10

// To Boolean: Used in conditional statements
if ("hello") { ... }   // Truthy: executes the block
if (0) { ... }         // Falsy: skips the block

Explicit Type Conversion Methods

This is when you intentionally convert a value using built-in functions.

Converting Values to Numbers

  • Number(value): Converts a value to a number. Returns NaN if it cannot be parsed.
  • parseInt(value) / parseFloat(value): Parses a string into an integer or floating-point number.
Number("3.14");  // 3.14
Number("  ");    // 0
Number("99px");  // NaN
parseInt("99px");// 99

Converting Values to Strings

  • String(value): Converts any data type to a string.
  • .toString(): A method available on numbers, booleans, and objects to convert them to strings (throws an error on null or undefined).
String(123);      // "123"
String(false);    // "false"
(500).toString(); // "500"

Converting Values to Booleans

Boolean(value): Evaluates whether a value is Truthy or Falsy.

Boolean(1);       // true
Boolean("hello"); // true

// Falsy values that always convert to false:
Boolean(0);       // false
Boolean("");      // false
Boolean(null);    // false
Boolean(undefined);// false
Boolean(NaN);     // false

Related entries: