Javascript - Regular expression (Regexp)

About

Multilingual Regular Expression Syntax (Pattern) in Javascript

Regular expressions operate at the level of code units. The single-character pattern (.) matches a single code unit (not a Text - Code point).

console.log(/^.$/.test("𐌰"));
console.log(/^..$/.test("𐌰"));

Syntax

  • The pattern enclosed between slashes. Loaded compilation (only when the script is loaded)
var pattern = /ni.o/; 
  • Runtime compilation (when the script runs, the regexp pattern can be dynamic)
var pattern = new RegExp("ni.o"); 

Example

Runtime

var pattern = new RegExp("ni.o"); 
console.log(pattern.test("nico"));
console.log(pattern.test("nikeau"));

Named Group

Named Group proposition

let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
console.log(result.groups.year); // '2015'
console.log(result.groups.month); // '01'
console.log(result.groups.day); // '02';

console.log(result[0]); // '2015-01-02';
console.log(result[1]); // '2015';
console.log(result[2]); // '01';
console.log(result[3]); // '02';

Named Group Replacement

let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = '2015-01-02'.replace(re, '$<day>/$<month>/$<year>');
console.log(result);// '02/01/2015'
  • Routing
re = new RegExp("/api/profiles/(?<id>[^/]*)");
let result = '/api/profiles/1'.replace(re, 'backend/api/profiles/profile.js?id=$<id>');
console.log(result);

Loaded

const REGEXP_EXP = /^PREFIZ_/i;
const raw = Object.keys(process.env)
    .filter(key => REGEXP_EXP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      }
    );

Library

Documentation / Reference


Powered by ComboStrap