regex in javascript

Regular expressions (or regex) are a powerful tool for pattern matching in JavaScript. They allow you to search through strings and identify patterns that match a certain structure, which can be very useful for tasks such as data validation and text processing.

Syntax:

To use regex in JavaScript, you need to create a RegExp object, which has a pattern (the text you want to search for) and optional flags for case-insensitivity, global and multi-line searches.

You can create a RegExp object using the constructor function:

index.tsx
const regex = new RegExp('pattern', 'flags');
46 chars
2 lines

Or using a literal notation:

index.tsx
const regex = /pattern/flags;
30 chars
2 lines

Flags:

  • g - Global search (finds all matches)
  • i - Case-insensitive search
  • m - Multi-line search

Methods:

JavaScript provides two methods for working with regular expressions:

  • test(): tests whether a string contains a match for the given pattern. It returns a boolean value.
index.tsx
const regex = /pattern/;
const str = 'string to test';
const result = regex.test(str); // true or false
104 chars
4 lines
  • match(): searches for matches within a string, and returns an array of match results.
index.tsx
const regex = /pattern/g;
const str = 'string to test';
const result = str.match(regex); // array of matches, or null if no matches found
138 chars
4 lines

Example:

index.tsx
const regex = /\d+/g; // matches one or more digits
const str = '123 some text 456';
const result = str.match(regex); // ['123', '456']
136 chars
4 lines

In this example, the regular expression matches one or more digits (represented by '\d+'), and the 'g' flag specifies a global search that should find all matches in the string. The match() method then returns an array containing all the matches that were found.

gistlibby LogSnag