JavaScript

Regular Expressions

regexName = /pattern/flags

regexName = new RegExp ("pattern", "flags")

RegExp consist of a pattern an optional flags. RegExp can be expressed using short or long syntaxes above.

Standard behaviour

Flags

There are only 6 flags in JavaScript:

RegExp cheatsheets:

Please also check: Capturing group.


Dinamically generated RegExp

The long new RegExp() syntax allows expression to be inserted, for example with ${...}, and therefore allow dinamically generated RegExp. This is not possible for the short syntax using slashes //. It can only contain static expression, that's known already duting the time the code is written. Which is most of the cases.

let tag = prompt("User tag:", "Kitten");
let tagRegex = new RegExp(`<${tag}>`);
tag;            "Kitten"
tagRegex;       /<Kitten>/

Searching using match()

stringName.match(regex)

Return values:


Replacing using replace()

stringName.replace(regex, "replacement")

Default method only replace the first match. To replace all matches, use flag g. Case-sensitive. Use flag i to make case-insensitive.

The replacement is in a string format "". We can insert fragment of the match using special character combinations below:

text = "cat dog lion";
text.replace(/dog/, "pig");     // 'cat pig lion'
text.replace(/dog/, "$& pig");  // 'cat dog pig lion'
text.replace(/dog/, "$` pig");  // 'cat cat  pig lion'
text.replace(/dog/, "$' pig");  // 'cat  lion pig lion'

testing using test()

regexName.test(string)

test()> looks for at least 1 match. If found, returns true. Otherwise, false.

statement = "I like dogs. Cats though, I love best.";
regex1 = /cat/i;
regex1.test(statement);     // true
regex2 = /lion/i;
regex2.test(statement);     // false