d
Amit DhamuSoftware Engineer
 

10 handy regular expressions

2 minute read 00000 views

Email address

const validateEmail = email =>
  new RegExp(/^[^\s@]+@[^\s@]+\.[^\s@]+$/).test(email)

Currency

const validateCurrency = currency =>
  new RegExp(/^\d+(?:\.\d{0,2})?$/).test(currency)

UK postcode

const validatePostcode = postcode =>
  new RegExp(/^[a-z]{1,2}\d[a-z\d]?\s*\d[a-z]{2}$/i).test(postcode)

UK landline number

const validateUkLandline = ukLandline =>
  new RegExp(/^0[12][0-9]{9}$/).test(ukLandline)

UK mobile number

const validateUkMobile = ukMobile => new RegExp(/^07[0-9]{9}$/).test(ukMobile)

Any UK number

const validateUkAny = ukAny => new RegExp(/^0[127][0-9]{9}$/).test(ukAny)

Any phone number

const validateAnyPhoneNumber = anyPhoneNumber =>
  new RegExp(/^([0-9]{0,16})$/).test(anyPhoneNumber)

URL

const validateUrl = url =>
  new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?').test(
    url
  )

Alternatively, we could use the URL API here:

const validateUrl = url => {
  try {
    return Boolean(new URL(url))
  } catch {
    return false
  }
}

Date ISO 8601

const validateDate = date =>
  new RegExp(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/).test(date)

Convert string to kebab case

const toKebabCase = value =>
  value
    .replace(/([a-z])([A-Z])/g, '$1-$2')
    .replace(/[^\w ]+/g, '')
    .replace(/ +/g, '-')
    .toLowerCase()