regular expression javascript validation code example

Example 1: how to validate a string using regular expression in javascript

function validate(){
  var phoneNumber = document.getElementById('phone-number').value;
  var postalCode = document.getElementById('postal-code').value;
  var phoneRGEX = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
  var postalRGEX = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
  var phoneResult = phoneRGEX.test(phoneNumber);
  var postalResult = postalRGEX.test(postalCode);
  alert("phone:"+phoneResult + ", postal code: "+postalResult);
}

Example 2: javascript regex

//Declare Reg using slash
let reg = /abc/
//Declare using class, useful for buil a RegExp from a variable
reg = new RegExp('abc')

//Option you must know: i -> Not case sensitive, g -> match all the string
let str = 'Abc abc abc'
str.match(/abc/) //Array(1) ["abc"] match only the first and return
str.match(/abc/g) //Array(2) ["abc","abc"] match all
str.match(/abc/i) //Array(1) ["Abc"] not case sensitive
str.match(/abc/ig) //Array(3) ["Abc","abc","abc"]
//the equivalent with new RegExp is
str.match('abc', 'ig') //Array(3) ["Abc","abc","abc"]