Logo with initials

How to use curly brackets with regular expressions

I was cleaning up a bad TSV the other day. I needed to select only 2 whitespaces. My problem was that \s selects whitespace, tabs and line breaks.

I found that curly brackets, or (curly braces) in regex allow you to capture a specific number of things.

How to capture only 2 whitespaces:

const regex = /[ ]{2}/g;
/// Feel free to change the number.

For two or more spaces, add a comma.

const regex = /[ ]{2,}/g;

You can use it on anything else, like a specific number of digits and numbers.

For example, here’s a quick and dirty regex to capture a UK postcode:

const regex = /[A-Z](\d*){2}/g;