Skip to main content

Common Regular Expression Use Cases (Live Playground)

Regular expressions are a powerful tool for solving many JavaScript problems. In this tutorial, we'll go through some common use cases where regular expressions can be employed to simplify your code and make it more robust.

Email Validation

Validating email addresses is a common task in web development. Here's an example of a regular expression for basic email validation:

const emailPattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
const email = 'example@email.com';
const isValidEmail = emailPattern.test(email);
console.log(isValidEmail); // true
Live Playground, Try it Yourself

Password Strength Checking

Regular expressions can be used to check the strength of a password. The following example checks if a password has at least one uppercase letter, one lowercase letter, one digit, and one special character:

const passwordPattern = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/;
const password = 'P@ssw0rd';
const isValidPassword = passwordPattern.test(password);
console.log(isValidPassword); // true
Live Playground, Try it Yourself

URL Parsing

You can use regular expressions to extract specific parts of a URL, such as the domain or protocol:

const urlPattern = /^(https?):\/\/([^\/]+)/;
const url = 'https://www.example.com/some-page';
const match = urlPattern.exec(url);
console.log(match); // ["https://www.example.com", "https", "www.example.com"]
Live Playground, Try it Yourself

Removing Whitespace

Regular expressions can be used to remove whitespace from the beginning and end of a string:

const whitespacePattern = /^\s+|\s+$/g;
const string = ' JavaScript is amazing! ';
const trimmedString = string.replace(whitespacePattern, '');
console.log(trimmedString); // 'JavaScript is amazing!'
Live Playground, Try it Yourself

Extracting Numbers

Extracting numbers from a string can be achieved using regular expressions:

const numberPattern = /\d+/g;
const string = 'The 3 little pigs built 1 house of straw, 1 house of wood, and 1 house of bricks.';
const numbers = string.match(numberPattern);
console.log(numbers); // ['3', '1', '1', '1']
Live Playground, Try it Yourself

Conclusion

Regular expressions are a powerful and versatile tool for solving common JavaScript problems. In this tutorial, we covered use cases such as email validation, password strength checking, URL parsing, whitespace removal, and number extraction. By applying regular expressions effectively, you can write more robust and efficient code to solve a wide range of text-processing tasks.