Javascript new regexp
In JavaScript, you can create a new regular expression object using the RegExp
constructor or the literal syntax.
Literal Syntax
const regex = /pattern/;
Where pattern
is the regular expression pattern you want to match.
Constructor Syntax
const regex = new RegExp("pattern");
Where pattern
is the regular expression pattern you want to match.
Options
You can also pass options to the RegExp
constructor to customize the behavior of the regular expression. The options are:
g
(global): matches all occurrences in the string, not just the first one.i
(ignore case): performs a case-insensitive match.m
(multiline): allows the^
and$
anchors to match at the beginning and end of each line, respectively.
For example:
const regex = new RegExp("pattern", "gi");
This regular expression will match all occurrences of the pattern in the string, ignoring case.
Properties and Methods
Regular expression objects have several properties and methods that you can use to work with the regular expression:
source
: returns the original regular expression pattern as a string.global
: returns a boolean indicating whether the regular expression is global.ignoreCase
: returns a boolean indicating whether the regular expression is case-insensitive.multiline
: returns a boolean indicating whether the regular expression allows multiline matching.test(string)
: returns a boolean indicating whether the regular expression matches the specified string.exec(string)
: returns an array containing the matched text and any captured groups.toString()
: returns a string representation of the regular expression.
For example:
const regex = /hello/i;
console.log(regex.source); // outputs "hello"
console.log(regex.test("Hello World")); // outputs true
console.log(regex.exec("Hello World")); // outputs ["Hello", index: 0, input: "Hello World"]