Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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"]
Comment

javascript regex reference

// Javascript Regex Reference
//  /abc/	A sequence of characters
//  /[abc]/	Any character from a set of characters
//  /[^abc]/	Any character not in a set of characters
//  /[0-9]/	Any character in a range of characters
//  /x+/	One or more occurrences of the pattern x
//  /x+?/	One or more occurrences, nongreedy
//  /x*/	Zero or more occurrences
//  /x?/	Zero or one occurrence
//  /x{2,4}/	Two to four occurrences
//  /(abc)/	A group
//  /a|b|c/	Any one of several patterns
//  /d/	Any digit character
// /w/	An alphanumeric character (“word character”)
//  /s/	Any whitespace character
//  /./	Any character except newlines
//  //	A word boundary
//  /^/	Start of input
//  /$/	End of input
Comment

javascript regex

// d	Any digit character
// w	An alphanumeric character (“word character”)
// s	Any whitespace character (space, tab, newline, and similar)
// D	A character that is not a digit
// W	A nonalphanumeric character
// S	A nonwhitespace character
// .	Any character except for newline
// /abc/	A sequence of characters
// /[abc]/	Any character from a set of characters
// /[^abc]/	Any character not in a set of characters
// /[0-9]/	Any character in a range of characters
// /x+/	One or more occurrences of the pattern x
// /x+?/	One or more occurrences, nongreedy
// /x*/	Zero or more occurrences
// /x?/	Zero or one occurrence
// /x{2,4}/	Two to four occurrences
// /(abc)/	A group
// /a|b|c/	Any one of several patterns
// /d/	Any digit character
// /w/	An alphanumeric character (“word character”)
// /s/	Any whitespace character
// /./	Any character except newlines
// //	A word boundary
// /^/	Start of input
// /$/	End of input
Comment

using regex in javascript

//Adding '/' around regex
var regex = /s/g;
//or using RegExp
var regex = new RegExp("s", "g");
Comment

javascript Create a RegEx

const reguarExp = new RegExp('abc');
Comment

javascript regex

const text="The quick brown FOX jumps over the lazy dog. The Fox..."

const regexLiteral = /fox/i; // Word fox case insensitive
const regex = new RegExp('fox', "i" /*case insenitive flag*/);
console.log(regex.toString()) // Outputs /fox/i => The definitions are the same

// Usage
const indexOfTheFirstMatch = text.search(/fox/i) // indexOfTheFirstMatch = 16
const withLowerCaseFirstFox = text.replace(/fox/i, "fox");
// The first occurrence of fox is uncapitalized. withLowerCaseFirstFox is 
// "The quick brown fox jumps over the lazy dog. The Fox..."
const withLowerCaseFox = text.replace(/fox/gi, "fox");
// All occurrences of  word fox are uncapitalized. withLowerCaseFox is 
// "The quick brown fox jumps over the lazy dog. The fox..."
// text.replaceAll(/fox/i, "fox") is equivalent to text.replace(/fox/gi, "fox")

const firstFoxText = text.match(/fox/g); // firstFoxText = ["FOX"] 
const foxOccurences = text.match(/fox/gi) // foxOccurences = ["FOX","Fox"]

// Check also regex methods: regex.match(), search(), replace(), etc.
Comment

js regrex

var s = "Please yes
make my day!";
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns 'yes
make my day'
Comment

regex in javascript

const regularExp = /abc/;
Comment

regex javscript

======
Match:
======

	[^pe]000 = except p and e everything match
	
	[pe]000	= only match p and e

=======
Ranges:
=======

	[a-z] , [b-h], [start, end]
	
	[a-zA-Z] -  both uppercase, lowercase
	
	[0-9] - 0 to 9 only
	
	but how 11 digits?? not single number??
	
	[0-9]+ - unlimited digits
	
	[0-9]{11} - only 11 digits
	
	[a-z]{11} - 11 letter word
	
	[a-z]{5,8} - 5 chars upto 8 chars
	
	[a-z]{5,} - minimum 5 and unlimited
	

==============
MetaCharacters:
==============
	
	Must have backslash on front otherwise it will behave as char...

	d - match any digit character (same as [0-9]) 
	w - match any word character (a-z, A-Z, 0-9 and _ underscores)
	s - match a whitespace char (spaces, tabs etc)
		 - match a tab char only
	
	EX:  d{3}sw{5}  -> first 3 numbers then space then 5 word chars
	
==============
Special Characters:
==============	

		+  -> one or more quantifier
	 
          ->  escape character or backslash
	
       []  ->   charset
	
       [^] ->	negate
       
       ?   ->   zero or 1     ex: a[a-z]?   must have a after that optional
       
       .   ->  any char except new line   
       			
       			 ex:  car.    carx true not newline char
       			 ex:  .+  any length string
       			 
       *   ->  0 or more bit like +
       
	       		ex: abc* - now include * aswell for match
       
       examples:
       
       ^w{5}$ -> must be 5 words for match
       
       			^ -> start
       			$ -> end
	
       (pet|toy|crazy)?rabbit
	
//===============================================================================//
// const reg2 = new RegExp(/[a-z]/,'i')
// const reg = /[a-z]/gi; // g-global, i-insensitive

const patterns = {
  tel: /^d{11}$/,
  username: /^w{5,12}$/i,
  pswd: /^[w@-]{8,20}$/,
  slug: /^[a-zd-]{8,20}$/,
  // 4 parts of email
  email: /^([a-zd.-]+)@([a-zd-]+).([a-z]{2,8})(.[a-z]{2,8})?$/,
};

const validate = (value, regex) => {
  const reg = regex.test(value);
  if (reg) {
    // add css class 'valid'
    return "Valid";
  } else {
    // add css class 'invalid'
    return "Invalid";
  }
};

validate("admin.fdsfsdfdsf@gmail.com", patterns["email"]);
	
//===============================================================================//
Comment

javascript regex

let str = 'hello world!';
let result = /^hello/.test(str);

console.log(result); // true
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript set class on div 
Javascript :: jquery change button click function 
Javascript :: sort strings javascript alphabetically 
Javascript :: complete math objects in javascript 
Javascript :: javascript loop object 
Javascript :: date get full year 
Javascript :: how to download file from link in react 
Javascript :: how to find all elements starting with class jquery 
Javascript :: file upload javascript 
Javascript :: javascript null or empty 
Javascript :: Pass object to query on Router.push NextJs 
Javascript :: javascript fibonacci example 
Javascript :: sort an array of objects in javascript 
Javascript :: how to get current month in express js 
Javascript :: convert a new date standard to a yyy-mm-dd format in javascript 
Javascript :: how to get all the voice channels in discord js 
Javascript :: numbered occurences in regex 
Javascript :: kendo treeview get selected node data 
Javascript :: node js run for loop asynchronously 
Javascript :: javascript loop x times 
Javascript :: array of images javascript 
Javascript :: async await javascript stack overflow 
Javascript :: array shuffle 
Javascript :: regex start line 
Javascript :: javascript compare two arrays of objects 
Javascript :: export gcp credentials json file 
Javascript :: types of loops in javascript 
Javascript :: get values inside json node js 
Javascript :: filter multidimensional array javascript 
Javascript :: js fibonacci sequence 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =