Javascript - Regular Expression Tips

Escaping

As we’ve seen, a backslash “" is used to denote character classes. So it’s a special character.

There are other special characters as well, that have special meaning in a regexp. They are used to do more powerful searches.

Here’s a full list of them: [ \ ^ $ . | ? * + ( ).

se the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

1
2
3
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

Syntax

1
2
3
/pattern/flags
new RegExp(pattern[, flags])
RegExp(pattern[, flags])

for the flags

  • g: global match; find all matches rather than stopping after the first match
  • i: ignore case; if u flag is also enabled, use Unicode case folding
  • m: multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
  • u: Unicode; treat pattern as a sequence of Unicode code points
  • y: sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).