Skip to main content

match

The match() function checks if a string matches a regular expression of a specified type.

Parameters

ParameterTypeDescription
strStringThe string to match against the regular expression.
paramRegexTypeThe type of regular expression to match against.

Returns

  • Boolean: true if the entire string matches the regular expression, false otherwise

Throws

  • Error: If the type argument is not one of the types specified in the regexs array

Regex types

ParameterDescription
emailMatches a valid email address.
urlMatches a valid URL.
credit-cardMatches a valid credit card number.
ip-addressMatches a valid IPv4 address.
postal-codeMatches a valid postal code.
passwordMatches a password that contains at least one uppercase letter, one lowercase letter, one digit, and one special character, and is at least 8 characters long.
usernameMatches a valid username that consists of alphanumeric characters, dots, underscores, and hyphens, and is at least 3 characters long.
timeMatches a valid time in the format HH:MM.
hashtagMatches a valid hashtag that starts with # and contains only alphanumeric characters.

Example

Email matching

const utils = require('utils-core.js');

const email = 'sif@sifedine.lol';
const isValidEmail = utils.regex.match(email, 'email');
console.log(isValidEmail);
//Output: true

Url matching

const utils = require('utils-core.js');

const url = 'https://www.sifedine.lol';
const isValidUrl = utils.regex.match(url, 'url');
console.log(isValidUrl);
//Output: true

Credit card matching

const utils = require('utils-core.js');

const cc = '4111111111111111';
const isValidCc = utils.regex.match(cc, 'credit-card
console.log(isValidCc);');
//Output: true

Ip address v4 matching

const utils = require('utils-core.js');

const ipAddress = '192.0.2.1';
const isValidIpAddress = utils.regex.match(ipAddress, 'ip-address
console.log(isValidIpAddress);-v4');
//Output: true

Password matching

const utils = require('utils-core.js');

const password = 'Password1!';
const isValidPassword = utils.regex.match(password, 'password');
console.log(isValidPassword);
//Output: true

Username matching

const utils = require('utils-core.js');

const username = 'john.doe';
const isValidUsername = utils.regex.match(username, 'username');
console.log(isValidUsername);
//Output: true

Time matching

const utils = require('utils-core.js');

const time = '18:30';
const isValidTime = utils.regex.match(time, 'time');
console.log(isValidTime);
//Output: true

Hashtag matching

const utils = require('utils-core.js');

const hashtag = '#example';
const isValidHashtag = utils.regex.match(hashtag, 'hashtag');
console.log(isValidHashtag);
//Output: true

See also

  • Regular expressions: Documents for regular expressions and how it works.
  • RegExr: Regular expression tester with syntax highlighting.