Mode modifier | Description | Example |
---|---|---|
i | Case insensitivity - Pattern matches upper or lowercase. | /aBc/i matches "abc" and "AbC". |
m | Multiline - Pattern with ^ and $ match beginning and end of any line in a multiline string. | /^ab/m matches the second line of "cab\nabc", and /ab$/m matches the first line. |
g | Global search - Pattern is matched repeatedly instead of just once. | /ab/g matches "ab" twice in "cababc". |
/<h1>(.*)<\/h1>/gUnfortunately this regular expression will extract the substring starting at the first <h1> tag in the string and ending at the last </h1> tag in the string. For example, if the string is "<h1>Fast</h1> ... <h1>Slow</h1> ..." then the above regular expression will match "Fast</h1> ... <h1>Slow". What we want in this case is the minimal possible match and we can get that by putting a ? after the * symbol (this works with the + symbol as well):
/<h1>(.*?)<\/h1>/gNow we will get the desired two matches of "Fast" and "Slow".
let dates = "03-06-1948 08-02-2021 12-31-1999"; let dateRegEx = /(\d{2})-(\d{2})-(\d{4})/g; let date = dateRegEx.exec(dates); while (date !== null) { console.log("Date: " + date[0] + " Year: " + date[3]); date = dateRegEx.exec(dates); }
const matches = str.matchAll(/(\d+)/); for (const match of matches) { ... }
command: "Hi Brad Smiley".replace(/\b(Brad)\b\s+\b(Smiley)\b/, "$2 $1"); result: "Hi Smiley Brad"