Read more

Using regular expressions in JavaScript

Dominik Schöler
December 07, 2015Software engineer at makandra GmbH

Regular expressions in Javascript are represented by a RegExp object. There also is a regex literal as in many other languages: /regex/. However, they are used slightly differently.

Regex literal

  • Usage: /foo+/
  • Shorthand for creating a regular expression object

RegExp() object

  • Usage: RegExp("foo+") or new RegExp("foo+")
  • No surrounding slashes required (they're the literal markers)
  • Since the argument is a string, backslashes need to be escaped as well: RegExp("\\d+")

Gotchas

matcher = new RegExp("foo", "g") // <- "global" flag
matcher.test("foobar") // => true
matcher.lastIndex // => 3 (where the regexp stopped scanning)
matcher.test("foobar") // => false
matcher.lastIndex // => 0
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

This does not happen when creating a new regex object each run, as with /foo/g.test("foobar"). Use String#match() if you want an array of matches.

Posted by Dominik Schöler to makandra dev (2015-12-07 08:31)