Skip to content

Instantly share code, notes, and snippets.

@TheShinriel
Created August 31, 2023 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheShinriel/788eeed988ceff74f47f3e88adfbe834 to your computer and use it in GitHub Desktop.
Save TheShinriel/788eeed988ceff74f47f3e88adfbe834 to your computer and use it in GitHub Desktop.
Show methods for RegEx in javascript and typescript
// --- Test() ---
let treasureMap = 'I found Gold';
let pirateAction = /found$/i;
let pirateObjective = /rum$/;
// Output: true
console.log(pirateAction.test(treasureMap));
// Output: false
console.log(pirateObjective.test(treasureMap));
// --- Search() ---
let treasureMap = 'I found GoLd';
let pirateSpeakA = /gold/;
let pirateSpeakB = /gold/i;
// Output: -1
console.log(treasureMap.search(pirateSpeakA));
// Output: 8
console.log(treasureMap.search(pirateSpeakB));
// --- Exec() ---
let sailorTalk = 'Ye want rum?';
let pirateRegex = /rum/;
// Output: rum
console.log(pirateRegex.exec(sailorTalk)[0]);
// Output: Ye want rum?
console.log(pirateRegex.exec(sailorTalk).input);
// --- Match() ---
let sailorTalk = 'We got Rum anD rUM';
let pirateRegex = /rum/gi;
// Output: [ "Rum", "rUM" ]
console.log(sailorTalk.match(pirateRegex));
// --- Split() ---
let treasureNote = 'This 123 note will b459e split by n42umbers';
let pirateRegex = /\d+/g;
// Output: [ "This ", " note will b", "e split by n", "umbers" ]
console.log(treasureNote.split(pirateRegex));
// --- MatchAll() ---
let pirateRegex = /t(e)(st(\d?))/g;
let pirateTalk = 'test1test2';
let crew = [...pirateTalk.matchAll(pirateRegex)];
// Output: ["test1", "e", "st1", "1"]
console.log(crew[0]);
// Output: ["test2", "e", "st2", "2"]
console.log(crew[1]);
// --- Repalace ---
let sailorTalk = 'We got Rum anD rUM';
let pirateRegex = /rum/i;
let pirateRegexGlobalFlag = /rum/gi;
// Output: We got ale and rUm?
console.log(sailorTalk.replace(pirateRegex, 'ale'));
// Output: We got ale anD ale
console.log(sailorTalk.replaceAll(pirateRegexGlobalFlag, 'ale'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment