Line boundary in JavaScript regexes

There are special characters that indicate the beginning '^' of or the end '$' of a string. Let's see how they work with examples.

Example

In this example, the search pattern is: replace 'aaa' with '!' only if it is at the beginning of the string:

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

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

'! aaa aaa'

Example

In this example, the search pattern is: replace 'aaa' with '!' only if it is at the end of the string:

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

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

'aaa aaa !'

Example

When '^' is at the beginning of the regex, and '$' is at the end, then in this way we check the entire string for compliance with the regex.

In the following example, the search pattern is: letter 'a' is repeated one or more times, replace the whole string with '!' if it consists of only letters 'a'.

let str = 'aaa'; let res = str.replace(/^a+$/g, '!');

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

'!'

Practical tasks

Given a string:

let str = 'abc def xyz';

Write a regex that will find the first substring of letters.

Given a string:

let str = 'abc def xyz';

Write a regex that will find the last substring of letters.

enru