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

// 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

regex js

'string'.match(/regex/);
  console.log('The 1quick5'.match(/[0-9]/g)); // ['1', '5']

/regex/.test('string');
console.log(new RegExp('foo*').test('table football')); //true

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

regular expression javascript

// Tests website Regular Expression against document.location (current page url)
if (/^https://example.com/$/.exec(document.location)){
	console.log("Look mam, I can regex!");
}
Comment

what is regular expression in javascript

let re = /ol/, 
Characters , ., cX, d, D, f, 
, 
, s, S, 	, v, w, W, , xhh, uhhhh, uhhhhh, []	
Assertions 	^, $, x(?=y), x(?!y), (?<=y)x, (?<!y)x, , B
Groups 		(x), (?:x), (?<Name>x), x|y, [xyz], [^xyz], Number	
Quantifiers *, +, ?, x{n}, x{n,}, x{n,m}
Unicode p{UnicodeProperty}, P{UnicodeProperty}	 property escapes
let defaults = new RegExp('compiled'); 
defaults = { dotAll: false, flags: "", global: false, ignoreCase: false, falselastIndex: 0, multiline: false, source: "abc", sticky: false, unicode: false}
Comment

js regex

// get "bucket1337" from https://bucket1337.appspot.com.storage.googleapis.com/staging/blender_input/162480.glb"

//define string
let string = "https://bucket1337.appspot.com.storage.googleapis.com/staging/blender_input/162480.glb"

//define regexp
let bucketRegex = new RegExp(`(?<=https://).*(?=.app)`, 'gm')

// execute regexp
let result = string.match(bucketRegex)[0]
Comment

regular expression javascript

console.log(/'d+'/.test("'123'"));
// → true
console.log(/'d+'/.test("''"));
// → false
console.log(/'d*'/.test("'123'"));
// → true
console.log(/'d*'/.test("''"));
// → true
Comment

javascript regular expression

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
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

js regular expression

Expression	Description
g    	Perform a global match (find all matches rather than stopping after the first match)
i	    Perform case-insensitive matching
m	    Perform multiline matching

[abc]	Find any character between the brackets
[^abc]	Find any character NOT between the brackets
[0-9]	Find any character between the brackets (any digit)
[^0-9]	Find any character NOT between the brackets (any non-digit)
(x|y)	Find any of the alternatives specified

.	Find a single character, except newline or line terminator
w	Find a word character
W	Find a non-word character
d	Find a digit
D	Find a non-digit character
s	Find a whitespace character
S	Find a non-whitespace character
	Find a match at the beginning/end of a word, beginning like this: HI, end like this: HI
B	Find a match, but not at the beginning/end of a word
	Find a NULL character

	Find a new line character
f	Find a form feed character

	Find a carriage return character
		Find a tab character
v	Find a vertical tab character
xxx	Find the character specified by an octal number xxx
xdd	Find the character specified by a hexadecimal number dd
udddd	Find the Unicode character specified by a hexadecimal number dddd

n+	Matches any string that contains at least one n
n*	Matches any string that contains zero or more occurrences of n
n?	Matches any string that contains zero or one occurrences of n
n{X}	Matches any string that contains a sequence of X n's
n{X,Y}	Matches any string that contains a sequence of X to Y n's
n{X,}	Matches any string that contains a sequence of at least X n's
n$	Matches any string with n at the end of it
^n	Matches any string with n at the beginning of it
?=n	Matches any string that is followed by a specific string n
?!n	Matches any string that is not followed by a specific string n

constructor	Returns the function that created the RegExp object's prototype
global	Checks whether the "g" modifier is set
ignoreCase	Checks whether the "i" modifier is set
lastIndex	Specifies the index at which to start the next match
multiline	Checks whether the "m" modifier is set
source	Returns the text of the RegExp pattern

compile()	Deprecated in version 1.5. Compiles a regular expression
exec()	Tests for a match in a string. Returns the first match
test()	Tests for a match in a string. Returns true or false
toString()	Returns the string value of the regular expression
Comment

regex js

function translatePigLatin(str) {
  let consonantRegex = /^[^aeiou]+/;
  let myConsonants = str.match(consonantRegex);
  return myConsonants !== null
    ? str
        .replace(consonantRegex, "")
        .concat(myConsonants)
        .concat("ay")
    : str.concat("way");
}

translatePigLatin("consonant");
Comment

regex in javascript

const regularExp = /abc/;
Comment

Regular expression javascript

^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*d)(?=.*[!#$%&? "]).*$

---

^.*              : Start
(?=.{8,})        : Length
(?=.*[a-zA-Z])   : Letters
(?=.*d)         : Digits
(?=.*[!#$%&? "]) : Special characters
.*$              : End
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 :: looping object 
Javascript :: prevent page scrolling when a modal is open 
Javascript :: check leap year 
Javascript :: loop backwards javascript 
Javascript :: getmonth javascript 
Javascript :: animation js 
Javascript :: chatbot js 
Javascript :: knexjs char 
Javascript :: search query in javascript 
Javascript :: knockout subscribe 
Javascript :: why null is an object in javascript 
Javascript :: loop,array javascript 
Javascript :: Finding palindrome using for loop 
Javascript :: javascript + Operator with Numbers 
Javascript :: javascript map size 
Javascript :: javascript this Inside Inner Function 
Javascript :: javascript function invocation 
Javascript :: how to write like query in node js 
Javascript :: Multiply string using a for loop 
Javascript :: manter alguns campos objetos javascript 
Javascript :: calculate age from date of birth javascript 
Javascript :: phaser add animation event 
Javascript :: javascript multiplication without operator 
Javascript :: npm deploy next js with tailwind 
Javascript :: Count the number of child records on the each parent object 
Javascript :: enum jpa jsf jakarta9 
Javascript :: this javascript 
Javascript :: class declaration in javascript 
Javascript :: Javascript Scrape content from a website source code 
Javascript :: vue sidebar 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =