# Multiline in JavaScript regexes

Regexes when working with multiline strings have their own features. Let's deal with them using an example of the following string usual characters, newlines and tabs characters:

`let str = `111 222 333 444`;`

## Newline

Newline characters can be caught with the `'\n'` command:

`let res = str.replace(/\n/g, '!');`

As a result, the following will be written to the variable (the spaces between the lines are tabulation):

``111! 222! 333! 444`;`

## Tabulation

Tab characters can be caught with the `'\t'` command:

`let res = str.replace(/\t/g, '!');`

As a result, the following will be written to the variable:

`` 111 !222 !333 !444 `;`

## Dot character

The `'.'` command for a multiline string doesn't catch newline characters:

`let res = str.replace(/./g, '!');`

As a result, the following will be written to the variable:

`` !!! !!!! !!!! !!!! `;`

## Any character

To catch all the characters in a multiline string, a tricky trick is used in the form of a `[\s\S]` combination. This construction will find all usual characters and all newlines:

`let res = str.replace(/[\s\S]/g, '!');`

As a result, the following will be written to the variable:

``!!!!!!!!!!!!!!!!!!`;`

## Hat

With the `'m'` modifier you can enable multiline mode. In this case, the hat will catch the beginning of each line:

`let res = str.replace(/^/gm, '!');`

As a result, the following will be written to the variable:

`` !111 !222 !333 !444 `;`

## Dollar

The `'$'` command in multiline mode will catch the end of each line:

`let res = str.replace(/$/gm, '!');`

As a result, the following will be written to the variable:

`` 111! 222! 333! 444! `;`

## Practical tasks

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

`` abc! def! ghi! jkl! `;`

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

`` ! abc ! def ! ghi ! jkl `;`

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

``! abc def ghi jkl !`;`

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

``! ! abc ! def ! ghi ! jkl !`;`

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

``! abc! def! ghi! jkl! !`;`

Given a string:

`` abc def ghi jkl `;`

Write a regex that will make this string the following:

`` !abc !def !ghi !jkl `;`
← →
↑
en ru