Change man to medieval French professor

String Literal Syntax in Character Classes

,

·

·

  • You can now (since ES 2024) use string literals in character classes within square brackets [] using the \q escape sequence. Eg: [\q{abc}def] which matches the string abc, or one of the characters d, e, or f
  • Previously you could only match single characters in character classes like [def] which matches one of the characters d, e or f, but not a string like ‘hello’
  • You need to use the 'v' flag for string literal syntax in character classes to work
  • If you want to match repetitions of abc or d or e or f, you can use /[\q{abc}def]+/v
let pattern = /[\q{abc}def]+/v
let targetString = "abcdefdfabcabcdddabc";
let result = targetString.match(pattern);
console.log(result[0]); //prints abcdefdfabcabcdddabc
targetString = ("abcdefadfabcabcdbddabcc");
result = targetString.match(pattern);
console.log(result[0]); //prints abcdef
  • The above pattern had to be written as /(abc|[def])+/ before String Literal Syntax
  • You can ‘or’ the strings to match any one of them
let pattern = /[\q{abc|xyz}def]+/v; //same as /[\q{abc}\q{xyz}def]+/v;
let targetString = "abcdefxyzdfabcabcddxyzdabc";
let result = targetString.match(pattern);
console.log(result[0]);
targetString = ("abcdexyzfadfabcabcdbddabcc");
result = targetString.match(pattern);
console.log(result[0]);
  • You can match any multiple character string including emojis. You can match any multiple character string including emojis. To match either 🙂or🤩 from among 🙂🙃🫠🤩😗
let pattern = /[\q{🙂|🤩}]+/gv
let targetString = "🙂🙃🫠🤩😗";
let results = targetString.matchAll(pattern);
for (let result of results) {
console.log(result[0]);
}
  • You can use set operations like union, subtraction and intersection but not negation
  • Subtraction
let pattern = /[[\q{abc|xyz|pqr}def]--[\q{pqr}]]+/v;
let targetString = "abcdefxyzdfabcabcddxyzdabc";
let result = targetString.match(pattern);
console.log(result[0]);
targetString = ("abcdexyzfadfabcabcdbddabcc");
result = targetString.match(pattern);
console.log(result[0]);
  • Intersection
let pattern = /[[\q{abc|xyz|pqr}def]&&[\q{abc}def]]+/v;
let targetString = "abcdefdfabcabcdddabc";
let result = targetString.match(pattern);
console.log(result[0]);
targetString = ("abcdexyzfadfabcabcdbddabcc");
result = targetString.match(pattern);
console.log(result[0]);
  • You cannot use negation
let pattern = /[^\q{xyz}def]+/v; //Syntax Error
let targetString = "abcdefdfabcabcdddabc";
let result = targetString.match(pattern);
console.log(result[0]);
targetString = ("abcdexyzfadfabcabcdbddabcc");
result = targetString.match(pattern);
console.log(result[0]);

Leave a Reply

Discover more from Programmer Lite

Subscribe now to keep reading and get access to the full archive.

Continue reading