Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created November 23, 2020 05:51
Show Gist options
  • Save whal-e3/47716abd7f1464b3f3c2d06037354b26 to your computer and use it in GitHub Desktop.
Save whal-e3/47716abd7f1464b3f3c2d06037354b26 to your computer and use it in GitHub Desktop.
JS regular expression (regex)
let reg, result, str;
reg = /hello/g; // global search
reg = /hello/;
reg = /hello/i; // i == flag : case insensitive
console.log(reg);
console.log(reg.source);
// exec() - result in array or null
result = reg.exec('hello world');
console.log(result);
console.log(result[0]);
console.log(result.index);
console.log(result.input);
// test() - true or false
result = reg.test('Hello');
console.log(result);
// match() - return first match (/g available)
str = 'Hello There';
result = str.match(reg);
console.log(result);
// search() - index of the first match if not -1
str = 'Hello There';
result = str.search(reg);
console.log(result);
// replace() - new string with some or all(/g) matches of a pattern
str = 'hello there hello';
const newStr = str.replace(reg, 'Hi');
console.log(newStr);
// ----------------------------------------------------------------------------------------------
let reg;
// Literal character
reg = /hello/;
reg = /hello/i;
// MetaCharacter symbols
reg = /^h/i; // Start with
reg = /ld$/i; // End with
reg = /^hello$/i;
reg = /h.llo/i; // Matches any ONE character
reg = /h*llo/i; // Matches any character (0 or more)
reg = /gre?a?y/i; // Optional char (char before ?)
reg = /gre?a?y\?/i; // Escape char (? as real ?)
// Brackets [] - Character sets
reg = /gr[ae]y/i; // a(A) or e(E)
reg = /[GF]ray/; // G or F
reg = /[^GF]ray/i; // anything except G or F
reg = /[A-Z]ray/; // A to Z
reg = /[a-z]ray/; // a to z
reg = /[A-Za-z]ray/; // a to z and A to Z
reg = /[0-9]ray/; // 0 to 9
reg = /[0-9][0-9]ray/; // 0 to 9
// Curly Braces {} - Quantifier
reg = /Hel{2}o/i; // {m} - char before {}, m times
reg = /Hel{2,4}o/i; // 2 to 4 times
reg = /Hel{2,}o/i; // at least 2 times
// Parentheses () - Grouping
reg = /([0-9]x){3}/;
// Shorthand Character Classes
reg = /\w/; // Word char - alphanumeric or _
reg = /\w+/; // + : one or more
reg = /\W/; // Non-word char - alphanumeric or _
reg = /\d/; //Match any digit
reg = /\d+/;
reg = /\D/; // Non-digit
reg = /\s/; // White space
reg = /\S/; // Non white space
reg = /Hell\b/i; // Word boundary
// Assertions
reg = /x(?=y)/; // Match x only if followed by y
reg = /x(?!y)/; // Match x only if NOT followed by y
// String to match
const str = 'dszxyft';
// Log result
const result = reg.exec(str);
console.log(result);
function reTest(reg, str) {
if (reg.test(str)) {
console.log(`${str} matches ${reg.source}`);
} else {
console.log(`${str} does NOT match ${reg.source}`);
}
}
reTest(reg, str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment