Skip to main content

@rtorcato/js-common / regex

regex

Functions

escapeRegExp()

escapeRegExp(str): string

Defined in: regex/index.ts:14

Escapes special regex characters in a string so it can be used in a RegExp.

Example

escapeRegExp('1 + 1 = 2?') // '1 \\+ 1 = 2\\?'
new RegExp(escapeRegExp('a.b')).test('a.b') // true
new RegExp(escapeRegExp('a.b')).test('axb') // false

Parameters

str

string

The string to escape.

Returns

string

The escaped string.


testRegex()

testRegex(str, pattern): boolean

Defined in: regex/index.ts:32

Tests if a string matches a given regex pattern.

Example

testRegex('hello world', /world/) // true
testRegex('hello world', '^hello') // true
testRegex('hello', /bye/) // false

Parameters

str

string

The string to test.

pattern

string | RegExp

The regex pattern (string or RegExp).

Returns

boolean

True if the string matches, false otherwise.


matchAll()

matchAll(str, pattern): RegExpMatchArray[]

Defined in: regex/index.ts:50

Returns all matches of a regex pattern in a string.

Example

matchAll('a1 b2 c3', /[a-z](\d)/).map((m) => m[1]) // ['1', '2', '3']
matchAll('nothing here', /\d/) // []

Parameters

str

string

The string to search.

pattern

string | RegExp

The regex pattern (string or RegExp).

Returns

RegExpMatchArray[]

An array of matches, or an empty array if none found.


replaceAllRegex()

replaceAllRegex(str, pattern, replacement): string

Defined in: regex/index.ts:69

Replaces all matches of a regex pattern in a string with a replacement.

Parameters

str

string

The string to search.

pattern

string | RegExp

The regex pattern (string or RegExp).

replacement

string | ((substring, ...args) => string)

The replacement string or function.

Returns

string

The resulting string.


splitByRegex()

splitByRegex(str, pattern): string[]

Defined in: regex/index.ts:90

Splits a string by a regex pattern.

Parameters

str

string

The string to split.

pattern

string | RegExp

The regex pattern (string or RegExp).

Returns

string[]

An array of strings.