Javascript - Regular expression (Regexp)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - 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("𐌰"));

Advertising

3 - 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"); 

4 - Example

4.1 - Runtime

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

4.2 - 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';

4.3 - 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);

Advertising

4.4 - 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;
      }
    );

5 - Library

6 - Documentation / Reference

web/javascript/es/regexp.txt · Last modified: 2019/05/14 09:56 by gerardnico