JavaScript Regular Expression - Methods

JavaScript Regular Expression - Methods

·

3 min read

Methods

A lot of methods in JavaScript can use regular expressions. They can be classified as two groups: string methods and regex methods.

string methods:

  • str.match
  • str.matchAll
  • str.split
  • str.search
  • str.replace
  • str.replaceAll

regex method:

  • regexp.exec
  • regexp.test

In this article, Let learn these methods one by one.

str.match

Used to get match values.

// return first match with format [ matched result, matched index, input string, matched groups ]
> "a b a c".match(/a/)
[ 'a', index: 0, input: 'a b a c', groups: undefined ]

// return all matches
> "a b a c".match(/a/g)
[ 'a', 'a' ]

// no match, return null
> "a b a c".match(/d/g)
null

str.matchAll

The improved version of str.match.

// must be called with global flag
> "a b a c".matchAll(/a/g)
Object [RegExp String Iterator] {}

// and return an Iterator
> const result = "a b a c".matchAll(/a/g);
> result
Object [RegExp String Iterator] {}

// iterator contents are standard matched result
> Array.from(result)
[
  [ 'a', index: 0, input: 'a b a c', groups: undefined ],
  [ 'a', index: 4, input: 'a b a c', groups: undefined ]
]

// no match returns iterator with empty array
> Array.from("a b a c".matchAll(/d/g))
[]

str.split

Used to split string into array.

// split string into array
> "1-2,3".split(/[-,]/)
[ '1', '2', '3' ]

// second parameter used to control split times
> "1-2,3".split(/[-,]/, 1)
[ '1' ]
> "1-2,3".split(/[-,]/, 2)
[ '1', '2' ]

str.search

Used to get matched position.

// return position of first match
> "a b c".search(/[bc]/)
2

// return -1 when not found
> "a b c".search(/[d]/)
-1

str.replace

Used to replace strings.

This method is very useful and pretty complicated, check my previous article The replace function in JavaScript.

str.replaceAll

Main differnce with replace method is that replaceAll will replace all matches.

// replace only replace first match
> "a b a".replace("a", "d")
'd b a'

// replace all replace all matches
> "a b a".replaceAll("a", "d")
'd b d'

// use replace with global flag to achieve the same effect
> "a b a".replace(/a/g, "d")
'd b d'

regex.exec

return matches for regular expression.

> /[ac]/.exec("a b c")
[ 'a', index: 0, input: 'a b c', groups: undefined ]

Use global flag to get all matches.

// 1. first create regex object
> const regex = /[ac]/g;
undefined

// then exec multiple times, temporary states lastIndex will be stored in the regex object
> regex.exec("a b c d a")
[ 'a', index: 0, input: 'a b c d a', groups: undefined ]

> regex.exec("a b c d a")
[ 'c', index: 4, input: 'a b c d a', groups: undefined ]

> regex.exec("a b c d a")
[ 'a', index: 8, input: 'a b c d a', groups: undefined ]

> regex.exec("a b c d a")
null

regex.test()

Check if there is a match return boolean values.

> /\d/.test("a")
false

> /\d/.test("a  1")
true

> /^\d/.test("a  1")
false