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.
There are only 6 flags in JavaScript:
i
: case-insensitiveg
: global. Looking for all matches.m
: multiline modes
: "dotall" mode. Allowing a dot .
to match newline character\n
.u
: full Unicode supporty
: Searching at exact opsition in the text.Please also check: Capturing group.
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>/
stringName.match(regex)
Return values:
g
:g
:0
and some additional details in properties.0
.g
):null
(instead of an empty array).
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:
$&
: insert the whole match.$`
: insert a part of the string before the match.$'
: insert a part of the string after the match.$n
: with n a 1-2 digit number. Inserts the contents of n-th parentheses.$<name>
: insert the content of the parentheses with the given name.
$$
: insert character $.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'
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